我正在尝试扫描计算机中的所有文件,包括子目录中的文件。该程序应在根文件夹“/”中启动。
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”, 有人知道为什么会发生这种情况吗?
最佳答案
发生这种情况是因为代码中没有任何内容可以更改进程的当前目录,或构建要扫描的目录的完整路径。
如果您在运行此命令时位于 /home/danny/src/
中,并在列出 /
时找到 dev
,您可以't opendir("dev")
,这意味着 /home/danny/src/dev
,而不是 /dev
。
关于c - 使用C扫描Linux中的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44780773/