tukuyo's blog

へっぽこまん

スポンサーリンク

ディレクトリ内のファイル名一覧を取得する【C++】【C++17】【filesystem】

filesystemについて

C++17からヘッダが実装されたらしい....
以前までは,WindowsMac,Linuxディレクトリ内のファイル名を取得するにはWin32APIを使ったり Boost Filesystem Libraryや<dirrent.h>を使ってコーディングしていたらしいが今後はヘッダのみでいろいろとできそうなきがする.

バージョン

  • Visual studio 2017以降(たぶん)
  • gcc8.1 リンクオプションに-lstdc++fsが必要
  • clang7.0 リンクオプションに-lc++fsが必要

実装方法

using namespace std;はあまり多用しないようにしてください.今回は見やすくするために使用しています.

#include <iostream>
#include <filesystem>

using namespace std;
namespace fs = std::experimental::filesystem;

int main() {
    fs::path path = "./directory";
    fs::directory_iterator itr(path), end;
    error_code err;

    for (itr;itr != end;itr.increment(err)) {
        if (err != errc::operation_not_permitted) {
            auto file = *itr;
            cout << file.path().filename() << endl;
        }
        else {
            break;
        }
    }

    system("PAUSE");
    return 0;
}

以上のソースコードで指定したディレクトリ内のファイル名・ディレクトリ名が出力されます.ファイルかディレクトリかを判定してファイル名のみ出力するのが以下のコードです.

#include <iostream>
#include <filesystem>

using namespace std;
namespace fs = std::experimental::filesystem;

int main() {
    fs::path path = "./directory";
    fs::directory_iterator itr(path), end;
    error_code err;

    for (itr;itr != end;itr.increment(err)) {
        if (err != errc::operation_not_permitted) {
            auto file = *itr;
            if(!fs::is_directory(file))
                cout << file.path().filename() << endl;
        }
        else {
            break;
        }
    }

    system("PAUSE");
    return 0;
}

is_directory()でディレクトリーかを調べることができる.

おわりに

filesystemを使うことでそこまで難しくなくファイル名を取得することができる.
vector を使ってファイル名を取得していろいろしたりできそう.
ただwstring型であることに注意

参考文献

cpprefjp.github.io cpprefjp.github.io qiita.com

スポンサーリンク