我正在尝试更改此代码以查找给定目录中的特定文件,并使用opendir()声明它是文件还是目录;
我一直在寻找如何做这一段时间,但我似乎无法找到或理解这样做的简单方法。
#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;
}
答案 0 :(得分: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
)。