在 Ubuntu 中,你可以使用 readdir 函数来读取目录内容
以下是一个简单的示例,展示了如何使用 readdir 过滤掉特定文件类型(例如 .txt 文件):
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir("."); // 打开当前目录
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
// 检查文件名是否以 .txt 结尾
if (strstr(entry->d_name, ".txt") == NULL) {
printf("%s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
这个程序会列出当前目录下的所有文件和文件夹,但不会显示以 .txt 结尾的文件。你可以根据需要修改 strstr(entry->d_name, ".txt") == NULL 这一行来过滤其他文件类型。