首页 > 解决方案 > 在 C++ 目录中搜索文件的函数输出错误

问题描述

我已经构建了这个函数来搜索某个目录中的文件。

一切正常,但是当我打印向量时,向量的输出是错误的。在 while 循环中,向量填充了正确的数据,但是当我在 while 循环之外(在下一个 for 循环中)输出它们时,数据不再相同。

我无法弄清楚出了什么问题。任何想法?

void search(const fs::path& directory, const fs::path& file_name, string input, string &compFileName, string &Fpath)
{
    string t;
    auto d = fs::recursive_directory_iterator(directory);
    auto found = std::find_if(d, end(d), [&](const auto & dir_entry)
    {
        Fpath = dir_entry.path().string();
        t = dir_entry.path().filename().string();
        return t.find(file_name.string()) != std::string::npos;
    }
    );

    if (found == end(d))
        cout << "File was not found" << endl;
    else
    {
        int count = 0;
        vector<LPCSTR> pfilesFound; //path
        vector<LPCSTR> nfilesFound; //name

        while (found != end(d))
        {
            count++;
            LPCSTR cFpath = Fpath.c_str();//get path and insert it in the shellexecute function
            LPCSTR ct = t.c_str();
            pfilesFound.push_back(cFpath);
            nfilesFound.push_back(ct);

            d++;
            found = std::find_if(d, end(d), [&](const auto & dir_entry)
            {
                Fpath = dir_entry.path().string();
                t = dir_entry.path().filename().string();
                return t.find(file_name.string()) != std::string::npos;
            });
        }

        cout << "We found the following items" << endl;
        int count2 = 0;
        for (std::vector<LPCSTR>::const_iterator i = nfilesFound.begin(); i != nfilesFound.end(); ++i)
        {
            count2++;
            std::cout << count2 << "- " << *i << endl;
        }
    }
}

标签: c++visual-studiosearchvectordirectory

解决方案


LPCSTR cFpath = Fpath.c_str();

这不是创建 的副本FPath,它只是提供指向存储实际字符串的原始内存的指针。

Fpath = dir_entry.path().string();

现在Fpath有不同的值,内部原始内存和您存储的指针现在也指向不同的值。

t.find(file_name.string()) != std::string::npos;被命中时,Fpath这里也被修改,这将被向量中所有存储的指针引用。


推荐阅读