C 如何在给定目录中查找特定文件并检查它是文件还是其他目录
我试图更改此代码以在给定目录中查找特定文件,并说明它是文件还是使用opendir的目录 我一直在寻找如何做到这一点有一段时间了,但我似乎无法找到或理解一个简单的方法来做到这一点C 如何在给定目录中查找特定文件并检查它是文件还是其他目录,c,linux,directory,C,Linux,Directory,我试图更改此代码以在给定目录中查找特定文件,并说明它是文件还是使用opendir的目录 我一直在寻找如何做到这一点有一段时间了,但我似乎无法找到或理解一个简单的方法来做到这一点 #include <sys/types.h> #include <dirent.h> #include <stdio.h> int main(int argc, char *argv[]){ DIR *dp; struct dirent *dirp; i
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
int main(int argc, char *argv[]){
DIR *dp;
struct dirent *dirp;
if(argc==1)
dp = opendir("./");
else
dp = opendir(argv[1]);
while ( (dirp = readdir(dp)) != NULL)
printf("%s\n", dirp->d_name);
closedir(dp);
return 0;
}
使用stat作为文件名,该文件名由目录名和readdir返回的名称连接而成。while循环如下所示:
char *path = "./";
if (argc == 2) {
path = argv[1];
}
dp = opendir(path);
while ((dirp = readdir(dp)) != NULL) {
char buf[PATH_MAX + 1];
struct stat info;
strcpy(buf, path);
strcat(buf, dirp->d_name);
stat(buf, &info); /* check for error here */
if (S_ISDIR(info.st_mode)) {
printf("directory %s\n", dirp->d_name);
} else if (S_ISREG(info.st_mode)) {
printf("regular file %s\n", dirp->d_name);
} else {
/* see stat(2) for other possibilities */
printf("something else %s\n", dirp->d_name);
}
}
在本例中,您需要包括一些附加标题sys/stat.h、unistd.h(用于stat)和string.h(用于strcpy和strcat)。find dir path-name file-print我不明白您在说什么,抱歉。我对系统编程相当陌生。你能更详细地解释一下吗?你不需要制造已经存在的东西。请看,man find是一个外部工具,出于任何原因,他可能需要在C代码中使用它。您能解释一下使用stat作为文件名是什么意思吗?将相对于当前目录的文件名传递给stat函数。刚才注意到您处理argv,因此修复了代码以列出所需的目录,不仅仅是当前的。有没有什么方法可以不使用stat标题来实现我想要做的事情?