物理の駅 Physics station by 現役研究者

テクノロジーは共有されてこそ栄える

std::filesystemを使ってディレクトリ(フォルダ)内にある全ファイルをリストしたりディレクトリを作成したり

VS2017 VS2019の環境では、 /std:c++latest または /std:c++17コンパイルオプションに追加する必要がある。

具体的な作業は、プロジェクトのオプション→C/C++→言語→C++言語標準 で /std:c++latest または /std:c++17 を追加する。/std:c++latest は実験的要素が強いので、筆者は /std:c++17を使っている

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main(int argc, char** argv) {

    if (argc == 1)return -1;
    fs::path path1(argv[1]);

    //ファイルをリスト化
    if (fs::is_directory(path1)) {
        std::cout << "Directory: " << fs::absolute(path1).string() << std::endl;
        std::cout << "Files: " << std::endl;
        auto dir_it = fs::directory_iterator(path1);
        for (auto &p : dir_it) {
            std::cout << p.path().string() << std::endl;
        }
    }
    //ディレクトリを作成
    auto path2 = path1 / "new_dir" ;
    fs::create_directory(path2);
}

/std:c++latest /std:c++17 の違いなどの詳細は下記のリンク参照

docs.microsoft.com