在C++目录中搜索文件的函数输出中出错

Error in output of function to search for files in directory C++

本文关键字:函数 输出 出错 文件 搜索 C++      更新时间:2023-10-16

我构建了这个函数来搜索特定目录中的文件。

一切都很好,但当我打印矢量时,矢量的输出是错误的。在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;
}
}
}

您正在存储指向字符串缓冲区的指针,这些指针在每次更改源字符串时都会失效。所以这两个向量基本上都充满了悬空指针。您需要像这样存储字符串:vector<::std::string> pfilesFound;

LPCSTR cFpath = Fpath.c_str();

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

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

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

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