Read file names from a directory

2019-01-09 01:31发布

I was wondering if there's an easy way in C++ to read a number of file names from a folder containing many files. They are all bitmaps if anyone is wondering.

I don't know much about windows programming so I was hoping it can be done using simple C++ methods.

标签: c++ file file-io
8条回答
劳资没心,怎么记你
2楼-- · 2019-01-09 01:50

Just had a quick look in my snippets directory. Found this:

vector<CStdString> filenames;
CStdString directoryPath("C:\\foo\\bar\\baz\\*");

WIN32_FIND_DATA FindFileData; 
HANDLE hFind = FindFirstFile(directoryPath, &FindFileData);

if (hFind  != INVALID_HANDLE_VALUE)
{
    do
    {
        if (FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
              filenames.push_back(FindFileData.cFileName);
    } while (FindNextFile(hFind, &FindFileData));

    FindClose(hFind);
}

This gives you a vector with all filenames in a directory. It only works on Windows of course.


João Augusto noted in an answer:

Don't forget to check after FindClose(hFind) for:

DWORD dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES) 
{
  // Error happened        
}

It's especially important if scanning on a network.

查看更多
倾城 Initia
3楼-- · 2019-01-09 01:51

Another alternative is -

  1. system("dir | findstr \".bmp\" > temp.txt ");
  2. Now read temp.txt line by line to get all filenames.
查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-09 01:53

I think you're looking for FindFirstFile() and FindNextFile().

查看更多
神经病院院长
5楼-- · 2019-01-09 01:57

Why not use glob()?

glob_t glob_result;
glob("/foo/bar/*",GLOB_TILDE,NULL,&glob_result);
for(unsigned int i=0;i<glob_result.gl_pathc;++i){
  cout << glob_result.gl_pathv[i] << endl;
}
查看更多
霸刀☆藐视天下
6楼-- · 2019-01-09 01:59

Boost provides a basic_directory_iterator which provides a C++ standard conforming input iterator which accesses the contents of a directory. If you can use Boost, then this is at least cross-platform code.

查看更多
唯我独甜
7楼-- · 2019-01-09 02:00

C++17 includes a standard way of achieve that

http://en.cppreference.com/w/cpp/filesystem/directory_iterator

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

int main()
{
    fs::create_directories("sandbox/a/b");
    std::ofstream("sandbox/file1.txt");
    std::ofstream("sandbox/file2.txt");
    for(auto& p: fs::directory_iterator("sandbox"))
        std::cout << p << '\n';
    fs::remove_all("sandbox");
}

Possible output:

sandbox/a
sandbox/file1.txt
sandbox/file2.txt
查看更多
登录 后发表回答