我想知道在C++中是否有一種簡單的方法來從包含多個文件的文件夾中讀取多個文件名。如果有人想知道,他們都是位圖。從目錄中讀取文件名
我對windows編程知之甚少,所以希望可以用簡單的C++方法來完成。
我想知道在C++中是否有一種簡單的方法來從包含多個文件的文件夾中讀取多個文件名。如果有人想知道,他們都是位圖。從目錄中讀取文件名
我對windows編程知之甚少,所以希望可以用簡單的C++方法來完成。
Boost提供了一個basic_directory_iterator
,它提供了一個符合C++標準的輸入迭代器,用於訪問目錄的內容。如果您可以使用Boost,那麼這至少是跨平臺的代碼。
我認爲你正在尋找FindFirstFile()
和FindNextFile()
。
注意:這些函數是Microsoft API的一部分,而不是C++標準的一部分。 – Twonky 2017-03-23 17:52:08
我建議您可以使用原生Win32 FindFirstFile()
和FindNextFile()
函數。這些使您可以完全控制如何搜索文件。這是簡單的C API,並不難用。
另一個優點是,由於C/C++庫層,Win32錯誤不會隱藏起來或變得更難獲取。
您也可以使用POSIX opendir()和readdir()函數。參見this manual page,它也有一些很好的示例代碼。
剛剛在我的snippets目錄中快速瀏覽過。找到這個:
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);
}
這給你一個目錄中的所有文件名的矢量。它當然只適用於Windows。
不要忘記FindClose(hFind)
後檢查:
DWORD dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES)
{
// Error happened
}
這是如果掃描在網絡上尤其重要。
另一種選擇是 -
system("dir | findstr \".bmp\" > temp.txt ");
爲什麼不使用3210?
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;
}
您忘記檢查glob()是否返回零,以及使用globfree()釋放已分配的glob_result。 – orbitcowboy 2016-05-20 19:01:20
C++ 17包括實現的標準方式
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");
}
可能的輸出:
sandbox/a
sandbox/file1.txt
sandbox/file2.txt
參見[我怎樣才能獲取列表使用C或C++的目錄中的文件](http://stackoverflow.com/questions/612097 /如何-可以-I-得到最列表的檔案-IN-A-目錄使用-C-或-C)。 – 2014-12-25 01:53:13