0

Is there a way that I can write a C function that gives me the file size for each file in a directory tree? (similar to the output of du -a)?

I don't have trouble getting any one of the file sizes, but I run into trouble recursing through directories within the main directory.

arc
  • 477
  • 2
  • 8
  • 14
  • possible duplicate of [How do you get a directory listing in C?](http://stackoverflow.com/questions/12489/how-do-you-get-a-directory-listing-in-c) – Keith Nicholas Feb 19 '13 at 20:30
  • You could look at the source code http://stackoverflow.com/questions/3264843/linux-du-command-source-code – Dipstick Feb 19 '13 at 20:36

2 Answers2

1

Is there a way that I can write a C function that gives me the file size for each file in a directory tree?

Yes, there is. You can use the <dirent.h> API to traverse a directory:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <dirent.h>
#include <sys/stat.h>

void recursive_dump(DIR *dir, const char *base)
{
    struct dirent *ent;
    for (ent = readdir(dir); ent != NULL; ent = readdir(dir)) {
        if (ent->d_name[0] == '.') {
            continue;
        }

        char fname[PATH_MAX];
        snprintf(fname, sizeof(fname), "%s/%s", base, ent->d_name);

        struct stat st;
        stat(fname, &st);

        if (S_ISREG(st.st_mode)) {
            printf("Size of %s is %llu\n", fname, st.st_size);
        } else {
            DIR *ch = opendir(fname);
            if (ch != NULL) {
                recursive_dump(ch, fname);
                closedir(ch);
            }
        }
    }
}

int main(int argc, char *argv[])
{
    DIR *dir = opendir(argv[1]);
    recursive_dump(dir, argv[1]);
    closedir(dir);

    return 0;
}
1

Yes. You need to use opendir and stat. See 'man 3 opendir', and 'man 2 stat'. In a nutshell:

#include <dirent.h>
#include <sys/stat.h>
// etc...

void the_du_c_function() {
   struct dirent direntBuf;
   struct dirent* dirEntry = 0;
   const char* theDir = ".";
   DIR* dir = opendir(theDir);
   while (readdir_r(dir,&direntBuf,dirEntry) && dirEntry) {
      struct stat filestat;
      char filename[1024];
      snprintf(filename,sizeof(filename),"%s/%s",theDir,dirEntry.d_name);
      stat(filename,&filestat);
      fprintf(stdout,"%s - %u bytes\n",filename,filestat.st_size);
   }
}

I just typed that code segment. I did not compile it, but that's the gist of it.

zapatero
  • 121
  • 4