Question: C programming - the following program should do the same thing as command du -ah /home It should be able to print out all of
C programming - the following program should do the same thing as command du -ah /home
It should be able to print out all of directories, subdirectories, files and the its size. But for some reason, I can't get the size right and been getting 0 size for some directories.
Each directory only print out 4.0K, which is wrong, it should be able to print out the total size.
#include
#include
#include
#include
#include
void listdir(char *name)
{
DIR *dir;
struct dirent *entry;
struct stat buf;
int size = 0;
double size_in_kb;
if(!(dir = opendir(name)))
return;
if (!(entry = readdir(dir)))
return;
while(entry = readdir(dir)){
if(entry->d_type == DT_DIR) {
char path[1024];
int len = snprintf(path, sizeof(path)-1, "%s/%s", name, entry->d_name);
path[len] = 0;
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
stat(path, &buf);
size= buf.st_size;
size_in_kb = size / 1024;
printf("%3.1fK %s/%s ",size_in_kb, name, entry->d_name);
listdir(path);
}
else{
stat(entry->d_name, &buf);
size= buf.st_size;
size_in_kb = size / 1024;
printf("%3.1fK %s/%s ", size_in_kb ,name, entry->d_name);
}
};
closedir(dir);
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
