溫馨提示×

如何用Debian readdir實現文件搜索

小樊
51
2025-03-14 13:17:43
欄目: 智能運維

在Debian系統中,readdir 是一個用于讀取目錄內容的函數,通常在C語言編程中使用。如果你想使用 readdir 實現文件搜索,你需要編寫一個C程序來遍歷目錄并檢查每個條目。以下是一個簡單的示例,展示了如何使用 readdir 來搜索特定類型的文件:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>

void searchFiles(const char *path, const char *filename) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;

    if (!(dir = opendir(path))) {
        perror("opendir");
        return;
    }

    while ((entry = readdir(dir)) != NULL) {
        // 構建完整的文件路徑
        char fullPath[1024];
        snprintf(fullPath, sizeof(fullPath), "%s/%s", path, entry->d_name);

        // 獲取文件狀態
        if (stat(fullPath, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        // 檢查是否是目錄,如果是則遞歸搜索
        if (S_ISDIR(statbuf.st_mode)) {
            if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
                searchFiles(fullPath, filename);
            }
        } else {
            // 檢查文件名是否匹配
            if (strstr(entry->d_name, filename) != NULL) {
                printf("Found: %s\n", fullPath);
            }
        }
    }

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <directory> <filename_pattern>\n", argv[0]);
        return EXIT_FAILURE;
    }

    searchFiles(argv[1], argv[2]);

    return EXIT_SUCCESS;
}

編譯和運行程序

  1. 將上述代碼保存到一個文件中,例如 search_files.c。
  2. 打開終端并導航到保存文件的目錄。
  3. 使用以下命令編譯程序:
gcc -o search_files search_files.c
  1. 運行程序并指定要搜索的目錄和文件名模式:
./search_files /path/to/search "pattern"

例如,如果你想在 /home/user/documents 目錄中搜索所有 .txt 文件,可以運行:

./search_files /home/user/documents "*.txt"

解釋

  • opendir 打開一個目錄流。
  • readdir 讀取目錄流中的下一個條目。
  • stat 獲取文件的狀態信息。
  • S_ISDIR 檢查一個文件是否是目錄。
  • strstr 檢查字符串中是否包含子字符串。

這個程序會遞歸地搜索指定目錄及其子目錄中的所有文件,并打印出匹配指定模式的文件路徑。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女