在Linux中,readdir
函數用于讀取目錄中的文件和子目錄。如果你想要篩選特定類型的文件,可以在讀取到每個文件名后,檢查其擴展名是否與你想要的類型匹配。
以下是一個使用C語言編寫的示例,展示了如何使用readdir
函數篩選特定文件類型(例如,只顯示.txt
文件):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
char path[1024];
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
while ((entry = readdir(dir)) != NULL) {
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
if (stat(path, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISREG(statbuf.st_mode)) {
char *ext = strrchr(entry->d_name, '.');
if (ext != NULL && strcmp(ext, ".txt") == 0) {
printf("%s\n", entry->d_name);
}
}
}
closedir(dir);
return EXIT_SUCCESS;
}
這個程序接受一個目錄作為命令行參數,然后使用readdir
函數讀取目錄中的每個條目。對于每個條目,我們使用stat
函數獲取文件的狀態信息,然后檢查它是否是一個常規文件(而不是目錄、符號鏈接等)。如果是常規文件,我們檢查其擴展名是否為.txt
。如果是,我們打印文件名。
要編譯此程序,請將其保存為filter_files.c
,然后運行以下命令:
gcc filter_files.c -o filter_files
現在你可以使用以下命令運行程序,篩選特定類型的文件:
./filter_files <directory>
將<directory>
替換為你想要篩選文件的目錄。