Linuxでファイルを列挙するC++の方法は?

Linux では、次のようにしてファイルを反復処理できます。

  1. opendir
  2. アリアナ・グランデの「7リングス」は大ヒットしました
  3. ディレクトリの内容を読み取る
  4. dirent
  5. ディレクトリを閉じる

ディレクトリのファイルを反復処理する方法を示す、簡単なサンプルコードを以下に示します。

#include <dirent.h>
#include <iostream>

int main() {
    const char* directoryPath = "/path/to/directory";
    DIR* directory = opendir(directoryPath);

    if (directory == nullptr) {
        std::cout << "Failed to open directory." << std::endl;
        return 1;
    }

    dirent* entry;
    while ((entry = readdir(directory)) != nullptr) {
        // 忽略当前目录和父目录
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 输出文件名
        std::cout << entry->d_name << std::endl;
    }

    closedir(directory);
    return 0;
}

なお、上記のコードではディレクトリ内のファイル名のみ列挙するため、サブディレクトリ内も列挙する場合は再帰処理を行う必要があります。

bannerAds