0

有没有一种方法可以编写一个 C 函数来为我提供目录树中每个文件的文件大小?(类似于 du -a 的输出)?

我在获取任何一种文件大小时都没有问题,但是在通过主目录中的目录递归时遇到了麻烦。

4

2 回答 2

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;
}
于 2013-02-19T21:10:34.187 回答
1

是的。您需要使用 opendir 和 stat。参见“man 3 opendir”和“man 2 stat”。简而言之:

#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);
   }
}

我刚刚输入了那个代码段。我没有编译它,但这就是它的要点。

于 2013-02-19T21:27:57.267 回答