在C++目录中搜索文件的函数输出中出错
Error in output of function to search for files in directory 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;
}
}
}
您正在存储指向字符串缓冲区的指针,这些指针在每次更改源字符串时都会失效。所以这两个向量基本上都充满了悬空指针。您需要像这样存储字符串: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
在这里也被修改,它将被向量中所有存储的指针引用。
相关文章:
- 如何从void函数输出字符串
- 简化C++包括变量名称和函数输出的模式
- 素数检查 C++ 函数输出非素数的数字
- 在C++目录中搜索文件的函数输出中出错
- 用于计算周长和面积的程序,而不是从 void 函数输出值
- 使用 if/else if 的函数输出问题
- (c++) 返回和函数输出之间的错误
- 使用函数输出最高平均值
- 为什么另一个函数输出错误的值
- C++函数输出泛型结构
- 在 c++11 中,是否仍然需要传入对接受函数输出的对象的引用
- 虚拟函数输出奇怪的值
- 将打印到控制台的函数输出重定向到字符串
- c++ 将函数输出重定向到编译的程序输入,反之亦然
- 未修改 CUDA 内核函数输出变量
- iomanip意外影响ctime函数输出
- 素数分解函数输出
- 继承构造函数输出
- 多维数组函数输出垃圾
- 递归函数-输出不正确