在Linux中,你可以使用readdir
函數來讀取目錄中的文件。如果你想要過濾掉特定的文件,可以在遍歷目錄時檢查文件名,并根據需要跳過那些你不想處理的文件。
以下是一個簡單的示例,展示了如何使用readdir
函數過濾掉名為.gitignore
的文件:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
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) {
// 過濾掉名為.gitignore的文件
if (strcmp(entry->d_name, ".gitignore") == 0) {
continue;
}
printf("%s\n", entry->d_name);
}
closedir(dir);
return EXIT_SUCCESS;
}
編譯這個程序:
gcc -o filter_files filter_files.c
運行程序,指定一個目錄作為參數:
./filter_files /path/to/directory
這個程序將輸出指定目錄中的所有文件和子目錄,除了名為.gitignore
的文件。
你可以根據需要修改過濾條件,例如使用通配符或其他字符串匹配方法來過濾掉更多的文件。