c++ - 在 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;
}
}
}
解决方案
LPCSTR cFpath = Fpath.c_str();
这不是创建 的副本FPath
,它只是提供指向存储实际字符串的原始内存的指针。
Fpath = dir_entry.path().string();
现在Fpath
有不同的值,内部原始内存和您存储的指针现在也指向不同的值。
当t.find(file_name.string()) != std::string::npos;
被命中时,Fpath
这里也被修改,这将被向量中所有存储的指针引用。
推荐阅读
- java - 如何使用配置文件在 docker 中启动 Spring Boot 应用程序?
- c++ - 在文件中写入和读取对象
- python - 如何将 TXT 文件中的 JSON 数据读入 Pandas
- c++ - 将 C++ 输出打印到文本文件
- amazon-web-services - 是否有任何选项可以查询和获取 IAM 政策的 ARN?
- cookies - 运行 testcafe 测试时如何避免写入浏览器 cookie?
- c# - 命名空间和表单名称的问题
- javascript - 将现有的 d3 实时流线图转换为使用经过的秒数而不是时间
- javascript - forEach() 方法只显示 1 个条目,如何让它们全部显示?
- mysql - 如果表 B 中存在数据,则覆盖表 A 中的数据,如果存在其他 ID 的外键,则映射到自己的覆盖数据