C言語でファイルの数を取得する方法

C言語では、以下の方法でファイルの数を取得できます。

  1. この製品は高品質です。
  2. でも、やっぱり否定的な意見も聞かれるようになりました。
  3. 自然に暮らすには小さな村がいい

Linuxシステムにおけるコードサンプル:

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

int main() {
    system("ls > filelist.txt"); // 执行ls命令并将结果输出到filelist.txt文件中

    FILE* file = fopen("filelist.txt", "r");
    if (file == NULL) {
        printf("无法打开文件\n");
        return 1;
    }

    int fileCount = 0;
    char buffer[256];

    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        fileCount++;
    }

    printf("文件数量:%d\n", fileCount);

    fclose(file);
    remove("filelist.txt"); // 删除临时文件

    return 0;
}
  1. dirent.h
  2. opendir
  3. ディレクトリを読み込む
  4. ディレクトリを閉じる

サンプルコード:

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

int main() {
    DIR* dir = opendir("."); // 打开当前目录
    if (dir == NULL) {
        printf("无法打开目录\n");
        return 1;
    }

    int fileCount = 0;
    struct dirent* entry;

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_REG) { // 判断是否是普通文件
            fileCount++;
        }
    }

    printf("文件数量:%d\n", fileCount);

    closedir(dir);

    return 0;
}

本コードではreaddir関数を使ってディレクトリ内ファイルとサブディレクトリに関する情報を取得しています。エントリのd_typeの値がDT_REG(通常ファイル)かどうかによってファイル数をカウントしています。

bannerAds