在Linux中,你可以使用readdir
函数来读取目录中的文件和子目录
首先,确保你已经包含了必要的头文件:
#include <dirent.h>
#include <stdio.h>
#include <string.h>
然后,你可以使用opendir
、readdir
和closedir
函数来读取目录中的内容。为了过滤特定文件类型,你可以检查每个条目的名称是否以所需的扩展名结尾。例如,如果你只想列出所有的.txt
文件,可以这样做:
#include <dirent.h>
#include <stdio.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir("."); // 打开当前目录
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
// 检查文件名是否以 ".txt" 结尾
if (strstr(entry->d_name, ".txt") != NULL) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
这个程序会打开当前目录(.
),然后使用readdir
函数读取其中的每个条目。对于每个条目,它使用strstr
函数检查文件名是否包含.txt
字符串。如果是,则打印文件名。
你可以根据需要修改这个示例,以便过滤其他类型的文件。只需将.txt
替换为你想要的扩展名即可。