简体   繁体   English

列出C ++目录中的所有文本文件

[英]List all text files in directory in C++

I am trying to store the name of all txt files in a directory in a string and print them out. 我正在尝试将所有txt文件的名称存储在字符串目录中并打印出来。 I need to count the number of txt files in the directory and then print the names. 我需要计算目录中txt文件的数量,然后打印名称。 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. 我找到了一些示例,但是它们在我正在使用的Visual Studio中不起作用。

Here is my code. 这是我的代码。

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 already has the first valid handle. FindFirstFile已经具有第一个有效的句柄。 If you immediately call FindNextFile then the first handle is lost. 如果立即调用FindNextFile则第一个句柄将丢失。 The file count in your example would be wrong. 您的示例中的文件计数将是错误的。

Use do-while loop istead. 使用do-while循环代替。

Also, the handle obtained from FindFirstFile must be closed with FindClose 此外,必须使用FindClose关闭从FindFirstFile获取的句柄。

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;

Use std::vector and std::wstring to store the items 使用std::vectorstd::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";

For some older compilers auto may not be available, use this instead 对于某些较早的编译器,可能无法使用auto ,请改用auto

for (int i = 0; i < vs.size(); i++)
    std::wcout << vs[i] << "\n";

Note, Windows API works with c-strings. 注意,Windows API使用c字符串。 In many cases you have to use .c_str() to obtain character array. 在许多情况下,您必须使用.c_str()获得字符数组。 For example: 例如:

if (vs.size())
{
    std::wstring str = vs[0];
    MessageBox(0, str.c_str(), 0, 0);
}

Here is a portable version using the new ISO Standard Filesystem Library TS (technical specification) for those with compilers that support it: 这是使用新的ISO标准文件系统库TS (技术规范)的可移植版本,适用于那些支持该标准的编译器:

#include <vector>
#include <iostream>
#include <algorithm>
#include <experimental/filesystem>

// for readability
namespace fs = std::experimental::filesystem;

/**
 * Function object to test directory entries
 * for a specific file extension.
 */
struct file_extension_is
{
    std::string ext;

    file_extension_is(std::string const& ext): ext(ext) {}

    bool operator()(fs::directory_entry const& entry) const
    {
        return entry.path().extension() == ext;
    }
};

int main(int, char* argv[])
{
    try
    {
        // directory supplied on the command line if present
        // else current directory
        fs::path dir = argv[1] ? argv[1] : ".";

        // place to store the results
        std::vector<fs::directory_entry> entries;

        // copy directory entries that have file extension ".txt"
        // to the results
        fs::directory_iterator di(dir);
        fs::directory_iterator end;

        std::copy_if(di, end, std::back_inserter(entries),
            file_extension_is(".txt"));

        // print it all out

        std::cout << "Number of files: " << entries.size() << '\n';

        for(auto const& entry: entries)
            std::cout << entry.path().string() << '\n';
    }
    catch(std::exception const& e)
    {
        std::cerr << e.what() << '\n';
    }
    catch(...)
    {
        std::cerr << "Unknown exception." << '\n';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM