溫馨提示×

如何用copendir獲取目錄文件數量

小樊
43
2025-08-18 07:35:16
欄目: 編程語言

opendir() 函數用于打開一個目錄流,而不是直接獲取目錄中的文件數量。要使用 opendir() 獲取目錄中的文件數量,你需要遍歷目錄并統計其中的文件。以下是一個使用 opendir()readdir() 函數獲取目錄中文件數量的示例:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>

int count_files_in_directory(const char *path) {
    DIR *dir;
    struct dirent *entry;
    int count = 0;

    dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return -1;
    }

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_REG) { // 只統計普通文件,可以根據需要修改
            count++;
        }
    }

    closedir(dir);
    return count;
}

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

    const char *path = argv[1];
    int file_count = count_files_in_directory(path);

    if (file_count >= 0) {
        printf("There are %d files in the directory: %s\n", file_count, path);
    }

    return EXIT_SUCCESS;
}

這個程序接受一個目錄路徑作為命令行參數,并輸出該目錄中的文件數量。請注意,這個示例僅統計普通文件(DT_REG),如果你還需要統計其他類型的文件(如目錄、符號鏈接等),可以根據需要修改 if 條件。

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