C trouble with stat

253 views Asked by At

In my program stat is only working for a current directory. Can any one please help me with this.

even though I am passing parameter from main it is only working for current directory. and source path is good it is printing correct path which I have passed from the main.

    DIR *dr;
    struct dirent *cur;
    struct stat fi;
    long int total_size = 0;
    dr = opendir(source);
    char *name;
    printf("%s\n\n\n", source);
    if (!(dr))
    {
       perror("opendir()");
       return(1);
    }

    while (cur = readdir(dr))
    {
        if(cur->d_name[0] != '.')
        {
            if(stat(cur->d_name, &fi) == -1)
            {
                printf("error \n\n");
            }
            else
            {
                printf("%s  ",cur->d_name);
                printf("%ld  ",fi.st_blocks);
                total_size = total_size + fi.st_blocks;
            }
        }
    }
    printf("\n\ntotal_size = %ld \n", total_size);
    printf("\n\n\n");
    return 0;

}

2

There are 2 answers

0
user3629249 On BEST ANSWER

cur->d_name only contains the file name.

to get a 'stat()' outside the current directory,

need to prefix with the path string.

Also need to check if the returned struct from readdir() is a file or a sub directory.

0
missimer On

The main problem is that stat expects a file path but d_name is just the file name. You can find a working example of how to use stat with d_name here