我正在尝试在 c 中创建一个函数,该函数扫描给定目录中是否有给定格式的文件(例如:- _sort.txt),并检查该目录是否包含该格式文件。
如果目录包含该格式的文件,那么它应该返回-1,否则返回0。 但我不知道如何扫描目录。任何人都可以帮助我吗?
我对 C 还很陌生,所以请耐心等待。
操作系统:- Linux
最佳答案
您可以使用strstr来查找文件名中的模式。
不要忘记包含这些 header :
#include
#include
int find_file(const char *pattern, DIR *dr) {
struct dirent *de;
int found = -1;
while ( (de = readdir(dr)) != NULL) {
// DT_REG is a regular file
if (de->d_type == DT_REG && strstr(de->d_name, pattern) != NULL) {
found = 0;
break;
}
}
return found;
}
任何您想要使用此功能的地方,您都应该传递使用opendir打开的DIR。
int main() {
DIR *d = opendir(".");
const char *pattern = "_sort.txt";
if (find_file(pattern, d) == 0)
printf("found it\n");
else
printf("not found it\n");
return 0;
}
有关直接结构的更多信息:
man readdir
关于c - 如何在c目录下查找文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64257738/