145

標準 C++ ですべてのファイル/ディレクトリを再帰的に反復するにはどうすればよいですか?

4

19 に答える 19

102

標準 C++ では、技術的にこれを行う方法はありません。標準 C++ にはディレクトリの概念がないためです。ネットワークを少し拡張したい場合は、Boost.FileSystemの使用を検討することをお勧めします。これは TR2 に含めることが認められているため、実装を可能な限り標準に近づける可能性が最も高くなります。

ウェブサイトから直接取った例:

bool find_file( const path & dir_path,         // in this directory,
                const std::string & file_name, // search for this name,
                path & path_found )            // placing path here if found
{
  if ( !exists( dir_path ) ) return false;
  directory_iterator end_itr; // default construction yields past-the-end
  for ( directory_iterator itr( dir_path );
        itr != end_itr;
        ++itr )
  {
    if ( is_directory(itr->status()) )
    {
      if ( find_file( itr->path(), file_name, path_found ) ) return true;
    }
    else if ( itr->leaf() == file_name ) // see below
    {
      path_found = itr->path();
      return true;
    }
  }
  return false;
}
于 2008-09-15T21:44:42.700 に答える
49

Win32 API を使用している場合は、FindFirstFileおよびFindNextFile関数を使用できます。

http://msdn.microsoft.com/en-us/library/aa365200(VS.85).aspx

ディレクトリを再帰的にトラバーサルするには、各WIN32_FIND_DATA.dwFileAttributesを調べて、FILE_ATTRIBUTE_DIRECTORYビットが設定されているかどうかを確認する必要があります。ビットが設定されている場合、そのディレクトリで関数を再帰的に呼び出すことができます。または、再帰呼び出しと同じ効果を提供するためにスタックを使用できますが、非常に長いパス ツリーのスタック オーバーフローを回避できます。

#include <windows.h>
#include <string>
#include <vector>
#include <stack>
#include <iostream>

using namespace std;

bool ListFiles(wstring path, wstring mask, vector<wstring>& files) {
    HANDLE hFind = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATA ffd;
    wstring spec;
    stack<wstring> directories;

    directories.push(path);
    files.clear();

    while (!directories.empty()) {
        path = directories.top();
        spec = path + L"\\" + mask;
        directories.pop();

        hFind = FindFirstFile(spec.c_str(), &ffd);
        if (hFind == INVALID_HANDLE_VALUE)  {
            return false;
        } 

        do {
            if (wcscmp(ffd.cFileName, L".") != 0 && 
                wcscmp(ffd.cFileName, L"..") != 0) {
                if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                    directories.push(path + L"\\" + ffd.cFileName);
                }
                else {
                    files.push_back(path + L"\\" + ffd.cFileName);
                }
            }
        } while (FindNextFile(hFind, &ffd) != 0);

        if (GetLastError() != ERROR_NO_MORE_FILES) {
            FindClose(hFind);
            return false;
        }

        FindClose(hFind);
        hFind = INVALID_HANDLE_VALUE;
    }

    return true;
}

int main(int argc, char* argv[])
{
    vector<wstring> files;

    if (ListFiles(L"F:\\cvsrepos", L"*", files)) {
        for (vector<wstring>::iterator it = files.begin(); 
             it != files.end(); 
             ++it) {
            wcout << it->c_str() << endl;
        }
    }
    return 0;
}
于 2008-09-15T21:47:50.260 に答える
33

新しいC++11範囲ベースforBoostを使用すると、さらに簡単にすることができます。

#include <boost/filesystem.hpp>

using namespace boost::filesystem;    
struct recursive_directory_range
{
    typedef recursive_directory_iterator iterator;
    recursive_directory_range(path p) : p_(p) {}

    iterator begin() { return recursive_directory_iterator(p_); }
    iterator end() { return recursive_directory_iterator(); }

    path p_;
};

for (auto it : recursive_directory_range(dir_path))
{
    std::cout << it << std::endl;
}
于 2013-10-18T15:11:32.743 に答える
26

迅速な解決策は、C のDirent.hライブラリを使用することです。

ウィキペディアの作業コード フラグメント:

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

int listdir(const char *path) {
    struct dirent *entry;
    DIR *dp;

    dp = opendir(path);
    if (dp == NULL) {
        perror("opendir: Path does not exist or could not be read.");
        return -1;
    }

    while ((entry = readdir(dp)))
        puts(entry->d_name);

    closedir(dp);
    return 0;
}
于 2012-09-02T23:15:00.170 に答える
11

上記のboost::filesystemに加えて、wxWidgets::wxDirQt:: QDirを調べたい場合があります。

wxWidgetsとQtはどちらも、オープンソースのクロスプラットフォームC++フレームワークです。

wxDirTraverse()またはより単純な関数を使用してファイルを再帰的にトラバースするための柔軟な方法を提供しますGetAllFiles()。同様にGetFirst()GetNext()関数を使用してトラバーサルを実装できます(Traverse()およびGetAllFiles()は、最終的にGetFirst()およびGetNext()関数を使用するラッパーであると想定しています)。

QDirディレクトリ構造とその内容へのアクセスを提供します。QDirを使用してディレクトリをトラバースする方法はいくつかあります。QDirIterator :: Subdirectoriesフラグでインスタンス化されたQDirIteratorを使用して、ディレクトリの内容(サブディレクトリを含む)を反復処理できます。もう1つの方法は、QDirのGetEntryList()関数を使用して、再帰的トラバーサルを実装することです。

これは、すべてのサブディレクトリを反復処理する方法を示すサンプルコード(ここから取得#例8-5)です。

#include <qapplication.h>
#include <qdir.h>
#include <iostream>

int main( int argc, char **argv )
{
    QApplication a( argc, argv );
    QDir currentDir = QDir::current();

    currentDir.setFilter( QDir::Dirs );
    QStringList entries = currentDir.entryList();
    for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry) 
    {
         std::cout << *entry << std::endl;
    }
    return 0;
}
于 2009-09-24T11:11:31.850 に答える
9

Boost::filesystem は、このタスクに非常に便利な recursive_directory_iterator を提供します。

#include "boost/filesystem.hpp"
#include <iostream>

using namespace boost::filesystem;

recursive_directory_iterator end;
for (recursive_directory_iterator it("./"); it != end; ++it) {
    std::cout << *it << std::endl;                                    
}
于 2014-05-05T14:52:23.810 に答える
6

私たちは2019年にいます.私たちはファイルシステムの標準ライブラリを持っていますC++. Filesystem libraryは、パス、通常のファイル、ディレクトリなど、ファイル システムとそのコンポーネントに対して操作を実行するための機能を提供します。

移植性の問題を検討している場合は、このリンクに重要な注意事項があります。それは言います:

階層ファイルシステムが実装にアクセスできない場合、または必要な機能を提供しない場合、ファイルシステムライブラリ機能は利用できない場合があります。基礎となるファイル システムでサポートされていない場合、一部の機能は使用できない場合があります (たとえば、FAT ファイル システムにはシンボリック リンクがなく、複数のハードリンクが禁止されています)。そのような場合、エラーを報告する必要があります。

ファイルシステム ライブラリはもともと として開発boost.filesystemされ、技術仕様 ISO/IEC TS 18822:2015 として公開され、最終的に C++17 で ISO C++ にマージされました。ブーストの実装は現在、C++17 ライブラリよりも多くのコンパイラとプラットフォームで利用できます。

@adi-shavit は、std::experimental の一部であったときにこの質問に回答し、2017 年にこの回答を更新しました。ライブラリについて詳しく説明し、より詳細な例を示したいと思います。

std::filesystem::recursive_directory_iteratorは、LegacyInputIteratorディレクトリの directory_entry 要素を反復し、すべてのサブディレクトリのエントリを再帰的に反復する です。各ディレクトリ エントリが 1 回だけアクセスされることを除いて、反復順序は規定されていません。

サブディレクトリのエントリを再帰的に反復したくない場合は、directory_iteratorを使用する必要があります。

どちらの反復子もdirectory_entryのオブジェクトを返します。、、などのdirectory_entryさまざまな便利なメンバー関数があります。メンバー関数はstd::filesystem::pathのオブジェクトを返し、それを使用して、、を取得できます。is_regular_fileis_directoryis_socketis_symlinkpath()file extensionfilenameroot name

以下の例を考えてみましょう。私はそれを使用Ubuntuして、ターミナル上でコンパイルしました

g++ example.cpp --std=c++17 -lstdc++fs -Wall

#include <iostream>
#include <string>
#include <filesystem>

void listFiles(std::string path)
{
    for (auto& dirEntry: std::filesystem::recursive_directory_iterator(path)) {
        if (!dirEntry.is_regular_file()) {
            std::cout << "Directory: " << dirEntry.path() << std::endl;
            continue;
        }
        std::filesystem::path file = dirEntry.path();
        std::cout << "Filename: " << file.filename() << " extension: " << file.extension() << std::endl;

    }
}

int main()
{
    listFiles("./");
    return 0;
}
于 2019-05-30T10:38:17.013 に答える
5

あなたはそうしない。C++ 標準にはディレクトリの概念がありません。文字列をファイルハンドルに変換するのは実装次第です。その文字列の内容とそのマッピング先は OS に依存します。C++ を使用してその OS を作成できるため、ディレクトリを反復処理する方法がまだ定義されていないレベルで使用されることに注意してください (ディレクトリ管理コードを作成しているため)。

これを行う方法については、OS API ドキュメントを参照してください。移植性が必要な場合は、さまざまな OS 用に多数の#ifdefを用意する必要があります。

于 2008-09-15T21:48:21.833 に答える
3

open()やなど、ファイルシステムのトラバーサル用に OS 固有の関数を呼び出す必要がありますreaddir()。C 標準では、ファイルシステム関連の関数は指定されていません。

于 2008-09-15T21:42:41.863 に答える
2

あなたはそうしない。標準 C++ は、ディレクトリの概念を公開していません。具体的には、ディレクトリ内のすべてのファイルを一覧表示する方法はありません。

system() 呼び出しを使用して結果を解析するのは恐ろしいハックです。最も合理的な解決策は、QtPOSIXなどのクロスプラットフォーム ライブラリを使用することです。

于 2008-09-15T21:47:25.207 に答える
1

Windows を使用している場合は、FindFirstFile を FindNextFile API と一緒に使用できます。FindFileData.dwFileAttributes を使用して、指定されたパスがファイルかディレクトリかを確認できます。ディレクトリの場合は、アルゴリズムを再帰的に繰り返すことができます。

ここでは、Windows マシン上のすべてのファイルを一覧表示するコードをまとめました。

http://dreams-soft.com/projects/traverse-directory

于 2014-05-17T15:34:41.383 に答える
0

ファイル ツリー ウォークftwは、ディレクトリ ツリー全体をパスで壁にする再帰的な方法です。詳細はこちら

注 :またはまたはftsのような隠しファイルをスキップできる を使用することもできます。....bashrc

#include <ftw.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>

 
int list(const char *name, const struct stat *status, int type)
{
     if (type == FTW_NS)
     {
         return 0;
     }

     if (type == FTW_F)
     {
         printf("0%3o\t%s\n", status->st_mode&0777, name);
     }

     if (type == FTW_D && strcmp(".", name) != 0)
     {
         printf("0%3o\t%s/\n", status->st_mode&0777, name);
     }
     return 0;
}

int main(int argc, char *argv[])
{
     if(argc == 1)
     {
         ftw(".", list, 1);
     }
     else
     {
         ftw(argv[1], list, 1);
     }

     return 0;
}

出力は次のようになります。

0755    ./Shivaji/
0644    ./Shivaji/20200516_204454.png
0644    ./Shivaji/20200527_160408.png
0644    ./Shivaji/20200527_160352.png
0644    ./Shivaji/20200520_174754.png
0644    ./Shivaji/20200520_180103.png
0755    ./Saif/
0644    ./Saif/Snapchat-1751229005.jpg
0644    ./Saif/Snapchat-1356123194.jpg
0644    ./Saif/Snapchat-613911286.jpg
0644    ./Saif/Snapchat-107742096.jpg
0755    ./Milind/
0644    ./Milind/IMG_1828.JPG
0644    ./Milind/IMG_1839.JPG
0644    ./Milind/IMG_1825.JPG
0644    ./Milind/IMG_1831.JPG
0644    ./Milind/IMG_1840.JPG

*.jpg, *.jpeg, *.png特定のニーズに合わせてファイル名を一致させたい場合 (例: すべてのファイルを検索する場合) fnmatch、.

 #include <ftw.h>
 #include <stdio.h>
 #include <sys/stat.h>
 #include <iostream>
 #include <fnmatch.h>

 static const char *filters[] = {
     "*.jpg", "*.jpeg", "*.png"
 };

 int list(const char *name, const struct stat *status, int type)
 {
     if (type == FTW_NS)
     {
         return 0;
     }

     if (type == FTW_F)
     {
         int i;
         for (i = 0; i < sizeof(filters) / sizeof(filters[0]); i++) {
             /* if the filename matches the filter, */
             if (fnmatch(filters[i], name, FNM_CASEFOLD) == 0) {
                 printf("0%3o\t%s\n", status->st_mode&0777, name);
                 break;
             }
         }
     }

     if (type == FTW_D && strcmp(".", name) != 0)
     {
         //printf("0%3o\t%s/\n", status->st_mode&0777, name);
     }
     return 0;
 }

 int main(int argc, char *argv[])
 {
     if(argc == 1)
     {
         ftw(".", list, 1);
     }
     else
     {
         ftw(argv[1], list, 1);
     }

     return 0;
 }
于 2020-07-21T02:25:59.917 に答える