【发布时间】:2017-06-27 12:51:18
【问题描述】:
我正在尝试扫描计算机中的所有文件,包括子目录中的文件。程序应在根文件夹“/”中启动。
logfind.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <stdlib.h>:
#include <dirent.h>
int is_directory(const char *path) {
struct stat path_stat;
stat(path, &path_stat);
return S_ISDIR(path_stat.st_mode);
}
void list_files(char *pathus) {
struct dirent *de;
DIR *dr = opendir(pathus);
if (dr == NULL) {
printf("Could not open current directory");
exit(1);
}
while ((de = readdir(dr)) != NULL) {
if (is_directory(de->d_name) > 0)
list_files(de->d_name);
else
printf("%s\n", de->d_name);
}
closedir(dr);
}
int main(int argc, char **argv) {
list_files("/");
return 0;
}
我运行它时得到的输出基本上是“logfind.c”很多次, 有人知道为什么会这样吗?
【问题讨论】:
-
你必须跳过像 .. 和 .当
de->d_name.和.. -
首先有点无关的仅供参考:
dirent结构已经包含一个类型,可用于查看条目是否为目录,无需stat调用。然后是主要部分:d_name中的名称不是完整路径。您需要将其附加到pathus中的当前路径。 -
如果你想省点麻烦,看看
man 3 ftw -
确保在访问
path_stat.st_mode之前检查stat的返回值 -
删除
dr ==NULLif 子句中的exit(1);,如果你得到一个权限被拒绝的错误,它应该报告错误并移动到下一个文件或目录。一件事。不要使用 printf 向标准输出报告错误,使用fprintf