LoginSignup
24
30

More than 5 years have passed since last update.

C++言語でディレクトリ内のファイル一覧取得(windows編)

Last updated at Posted at 2015-11-23

C++言語でよくディレクトリ内のファイルを取得したいことがあるのでまとめてみました.ファイルの一覧の取得,拡張子を指定して取得について実装例をもとに解説をしていきたいと考えています.

  1. ディレクト内のファイルの一覧の取得
  2. 拡張子を考慮したディレクトリ内のファイルの一覧の取得

拡張子を考慮したディレクト内のファイルの一覧の取得

#include <Windows.h>
#include <vector>
#include <string>
#include <stdexcept>
std::vector<std::string> get_file_path_in_dir(const std::string& dir_name , const std::string& extension) noexcept(false)
{
    HANDLE hFind;
    WIN32_FIND_DATA win32fd;//defined at Windwos.h
    std::vector<std::string> file_names;

    //拡張子の設定
    std::string search_name = dir_name + "\\*." + extension;

    hFind = FindFirstFile( search_name.c_str() , &win32fd);

    if (hFind == INVALID_HANDLE_VALUE) {
        throw std::runtime_error("file not found");
    }

    do {
        if ( win32fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
        }
        else {
            file_names.push_back(win32fd.cFileName);
            printf("%s\n", file_names.back().c_str() );

        }
    } while (FindNextFile(hFind, &win32fd));

    FindClose(hFind);

    return file_names;
}

 基本的にはFindFirstFileで指定したディレクトリの調査を行います.win32fd.cFileNameで探索したファイル名の取得を行い(ファイル名のみ),FindNextFileで次のファイルへと行きます.そして,最後にFindCloseをして終了です.

注意事項
- ファイル名はワイルドカードで指定(C:\\*.*)する.

参考にしたサイト
http://d.hatena.ne.jp/s-kita/20100129/1264776052

24
30
2

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
24
30