溫馨提示×

如何使用readdir統計文件數量

小樊
56
2025-06-05 23:49:08
欄目: 編程語言

readdir 是一個用于讀取目錄內容的函數,通常在 C 或 C++ 語言中使用。要使用 readdir 統計文件數量,你需要遍歷目錄中的所有條目,并檢查每個條目是否為文件。以下是一個使用 readdir 統計文件數量的示例:

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

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <directory_path>\n", argv[0]);
        return 1;
    }

    DIR *dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

    struct dirent *entry;
    int file_count = 0;

    while ((entry = readdir(dir)) != NULL) {
        // 跳過當前目錄(.)和上級目錄(..)
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 使用 stat 函數獲取文件信息
        struct stat file_stat;
        if (stat(argv[1] "/" entry->d_name, &file_stat) == 0) {
            // 檢查是否為文件
            if (S_ISREG(file_stat.st_mode)) {
                file_count++;
            }
        }
    }

    closedir(dir);

    printf("Number of files: %d\n", file_count);
    return 0;
}

這個程序接受一個目錄路徑作為命令行參數,然后使用 readdir 函數遍歷目錄中的所有條目。對于每個條目,我們使用 stat 函數獲取文件信息,并檢查它是否為普通文件(而不是目錄、符號鏈接等)。最后,我們輸出文件數量。

要編譯此程序,請使用以下命令:

gcc -o count_files count_files.c

然后運行程序,傳遞一個目錄路徑作為參數:

./count_files /path/to/directory

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