gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:31:13 25 4
gpt4 key购买 nike

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

一切正常,但是当我打印 vector 时, vector 的输出是错误的。在 while 循环内, vector 中填充了正确的数据,但是当我在 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 基本上都充满了悬空指针。您需要像这样存储字符串:vector<::std::string> pfilesFound; .

关于c++ - 在目录 C++ 中搜索文件的函数输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51439072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com