在 Linux 中,opendir() 函數用于打開一個目錄流,以便后續使用 readdir() 函數讀取目錄中的條目。結合這兩個函數,可以實現一個簡單的文件搜索功能。以下是一個示例代碼,展示如何使用 opendir() 和 readdir() 來遍歷目錄并查找特定類型的文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void search_files(const char *path, const char *extension) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
// 打開目錄
if (!(dir = opendir(path))) {
perror("opendir");
return;
}
// 遍歷目錄中的條目
while ((entry = readdir(dir)) != NULL) {
// 跳過當前目錄和上級目錄的特殊條目
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 構建完整的文件路徑
char full_path[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
// 獲取文件信息
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
// 檢查是否為目錄,如果是則遞歸搜索
if (S_ISDIR(statbuf.st_mode)) {
search_files(full_path, extension);
}
// 檢查文件擴展名是否匹配
else if (strstr(entry->d_name, extension) != NULL) {
printf("Found file: %s\n", full_path);
}
}
// 關閉目錄
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <directory> <extension>\n", argv[0]);
return EXIT_FAILURE;
}
search_files(argv[1], argv[2]);
return EXIT_SUCCESS;
}
opendir(): 打開一個目錄流。readdir(): 讀取目錄流中的下一個條目。stat(): 獲取文件或目錄的信息。S_ISDIR(): 檢查文件是否為目錄。strstr(): 檢查文件名中是否包含指定的擴展名。編譯并運行程序,傳入要搜索的目錄路徑和文件擴展名。例如:
gcc -o search_files search_files.c
./search_files /path/to/search .txt
這個程序會遞歸地搜索指定目錄及其子目錄中的所有 .txt 文件,并打印出它們的完整路徑。