就像构造递归调用的路径一样,您必须使用前导目录构造文件名 stat 系统调用。您的程序仅适用于当前目录中的文件。
stat
修复程序的有效方法是将足够大的缓冲区传递给递归函数,并逐步构建路径和文件名:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/stat.h> #include <dirent.h> long int du_function(char path[], size_t size) { size_t len = strlen(path); long int total = 0; struct stat sfile; struct dirent *de; DIR *dr = opendir(path); if (dr == NULL) { printf("Could not open directory %s\n", path); return 0; } while ((de = readdir(dr)) != NULL) { if (strcmp(de->d_name, "..") == 0) continue; //printf("%s\n", de->d_name); if (snprintf(path + len, size - len, "/%s", de->d_name) > (int)(size - len)) { path[len] = '\0'; printf("Path too long: %s/%s\n", path, de->d_name); continue; } stat(path, &sfile); if (S_ISDIR(sfile.st_mode) && strcmp(de->d_name, ".") != 0) { //printf("This is a directory called %s\n", path); total = total + du_function(path, size); } else if (S_ISREG(sfile.st_mode) || strcmp(de->d_name, ".") == 0) { //printf("Size in bytes = %ld\n", (long)sfile.st_size); total = total + sfile.st_size; //printf("The total is %ld bytes so far.\n", total); } } path[len] = '\0'; printf("%ld\t%s\n", total, path); closedir(dr); return total; } int main(int argc, char *argv[]) { char path[1024] = "."; if (argc > 1) { strcpy(path, argv[1]); } du_function(path, sizeof path); return 0; }