LoginSignup
40

More than 5 years have passed since last update.

ディレクトリ内にある全ファイル/ディレクトリを列挙する

Last updated at Posted at 2013-12-06
#include <iostream>
#include <algorithm>
#include <filesystem> // std::tr2::sys::path etc.

using namespace std;

int main() {
    namespace sys = std::tr2::sys;
    sys::path p("."); // 列挙の起点
    std::for_each(sys::directory_iterator(p), sys::directory_iterator(),
    //  再帰的に走査するならコチラ↓
    //  std::for_each(sys::recursive_directory_iterator(p), sys::recursive_directory_iterator(),
        [](const sys::path& p) {
            if (sys::is_regular_file(p)) { // ファイルなら...
                cout << "file: " << p.filename() << endl;
            } else if (sys::is_directory(p)) { // ディレクトリなら...
                cout << "dir.: " << p.string() << endl;
            }
        });
}

実行例:

file: ConsoleApplication1.vcxproj
file: ConsoleApplication1.vcxproj.filters
file: ConsoleApplication1.vcxproj.vspscc
dir.: ./Debug
dir.: ./Release
file: Source.cpp
file: trial.txt

[追記] ワイド文字版はコチラ

int main() {
    namespace sys = std::tr2::sys;
    sys::wpath p(L"."); // 列挙の起点
    std::for_each(sys::wdirectory_iterator(p), sys::wdirectory_iterator(),
    //  再帰的に走査するならコチラ↓
    //  std::for_each(sys::wrecursive_directory_iterator(p), sys::wrecursive_directory_iterator(),
        [](const sys::wpath& p) {
        if (sys::is_regular_file(p)) { // ファイルなら...
            wcout << L"file: " << p.filename() << endl;
        }
        else if (sys::is_directory(p)) { // ディレクトリなら...
            wcout << L"dir.: " << p.string() << endl;
        }
    });
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40