在Ubuntu中,你可以使用readdir
函数来读取目录内容。为了过滤特定类型的文件,你可以在遍历目录时检查每个文件的扩展名。以下是一个使用C语言编写的示例,展示了如何使用readdir
函数过滤特定类型的文件:
#include#include #include #include #include int main(int argc, char *argv[]) { if (argc != 3) { printf("Usage: %s \n", argv[0]); return 1; } const char *dir_path = argv[1]; const char *ext = argv[2]; DIR *dir = opendir(dir_path); if (dir == NULL) { perror("opendir"); return 1; } struct dirent *entry; while ((entry = readdir(dir)) != NULL) { // 获取文件名 char *filename = entry->d_name; // 检查文件扩展名 if (strstr(filename, ext) != NULL) { printf("%s\n", filename); } } closedir(dir); return 0; }
编译并运行这个程序,传入要读取的目录路径和要过滤的文件扩展名。例如,如果你想列出目录中所有的.txt
文件,可以这样运行:
gcc filter_files.c -o filter_files ./filter_files /path/to/directory .txt
这个程序会输出指定目录中所有扩展名为.txt
的文件。