列出C ++目录中的所有文本文件 [英] List all text files in directory in C++
问题描述
我正在尝试将所有txt文件的名称存储在字符串目录中并打印出来.我需要计算目录中txt文件的数量,然后打印名称.计数的一部分正在起作用,但是我似乎无法使这个名字起作用.我找到了一些示例,但是它们在我正在使用的Visual Studio中不起作用.
I am trying to store the name of all txt files in a directory in a string and print them out. I need to count the number of txt files in the directory and then print the names. The part of counting is working, but I can't seem to get the name working. I have found some examples but they don't work in visual studio which is what I'm using.
这是我的代码.
int main() {
bool x = true;
int i = 0;
wchar_t* file = L"../Menu/Circuitos/*.txt";
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind = FindFirstFile(file, &FindFileData);
if (hFind != INVALID_HANDLE_VALUE) {
i++;
while ((x = FindNextFile(hFind, &FindFileData)) == TRUE) {
i++;
}
}
cout << "number of files " << i << endl;
return 0;
}
推荐答案
FindFirstFile
已经具有第一个有效句柄.如果立即调用FindNextFile
,则第一个句柄将丢失.您的示例中的文件计数将是错误的.
FindFirstFile
already has the first valid handle. If you immediately call FindNextFile
then the first handle is lost. The file count in your example would be wrong.
使用do-while
循环代替.
此外,必须使用FindClose
HANDLE hFind;
hFind = FindFirstFile(file, &FindFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
do {
wcout << FindFileData.cFileName << "\n";
i++;
} while (FindNextFile(hFind, &FindFileData));
FindClose(hFind);
}
cout << "number of files " << i << endl;
使用std::vector
和std::wstring
存储项目
#include <string>
#include <vector>
...
std::vector<std::wstring> vs;
HANDLE hFind;
hFind = FindFirstFile(file, &FindFileData);
if (hFind != INVALID_HANDLE_VALUE)
{
do {
vs.push_back(FindFileData.cFileName);
} while (FindNextFile(hFind, &FindFileData));
FindClose(hFind);
}
std::cout << "count:" << vs.size() << "\n";
for (auto item : vs)
std::wcout << item << "\n";
对于某些较旧的编译器auto
可能不可用,请改用此
For some older compilers auto
may not be available, use this instead
for (int i = 0; i < vs.size(); i++)
std::wcout << vs[i] << "\n";
请注意,Windows API使用c字符串.在许多情况下,您必须使用.c_str()
来获取字符数组.例如:
Note, Windows API works with c-strings. In many cases you have to use .c_str()
to obtain character array. For example:
if (vs.size())
{
std::wstring str = vs[0];
MessageBox(0, str.c_str(), 0, 0);
}
这篇关于列出C ++目录中的所有文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!