forsb
forsb

Reputation: 135

using lstat() on directories and getting incorrect answers

Im currently trying to build a program that gives the same output as du -s does. However i have found myself with a bug that i can't understand. My program will give me 8 less than the correct answer, for very large directories the answer also differ but then it's by more. For smaller directories it always gives me 8 less, no mather how many directories there is inside a directories etc.

My first thought was that i was not adding the size of the actuall directories disc usage and therefore fell short on the answer but that was not the issue. I also thought that i maybe generate corrupt paths for when i want to check a file inside of directory but then i would get a error printed since the file wouldn't be able to stat().

The following code is how i add upp the size for the files/directories, will st_blocks not give the correct size for directories? (i then divide this answer by 2)

        struct stat sb;
             if(lstat(file, &sb) == -1){
             perror(file);
             exit(EXIT_FAILURE);
        }
        *size += sb.st_blocks;

The basics of the rekursion i use to go trough is:

   while((entry = readdir(dir)) != NULL){
        if(!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")){
            continue;
        }
        else if(entry->d_type == DT_DIR){
            char path[1024];
            generate_path(path, dir_name, entry->d_name);
            traverse_dir(path, total_size);
            get_size_from_dir(path, total_size);

        }
        else{
            char path[1024];
            generate_path(path, dir_name, entry->d_name);
            get_size_from_single_file(path, total_size);
        }
    }

Where i get the size of the orignal directory outside of this funtion. Is it wrong for me to use st_blocks? I have tried using st_size but then i don't get close to the correct answer since it says that all my files has the size of 4096. Im new to this and don't have enough deep knowledge of how lstat works since it's my first time using it, i have read trough the manual but don't really understand what i do wrong. Could anyone point me towards the right direction?

Upvotes: 1

Views: 912

Answers (1)

bruno
bruno

Reputation: 32596

warning :

  • on an empty directory du returns 4, your program will return 0 (no files)

  • on a dir without file but containing an empty dir du -s returns 8 (4+4) and your program will return 0 (no files)

  • etc

so du returns not only the size needed by the files but also by the dir(s), but your program only consider the files => your program computes less than du

Upvotes: 1

Related Questions