C++ 在目录C+;中搜索文件的函数输出出错+;
我构建了这个函数来搜索某个目录中的文件 一切正常,但当我打印向量时,向量的输出是错误的。在while循环内部,向量被正确的数据填充,但是当我在while循环外部(在下一个for循环中)输出它们时,数据不再相同 我想不出是怎么回事。有什么想法吗C++ 在目录C+;中搜索文件的函数输出出错+;,c++,visual-studio,search,vector,directory,C++,Visual Studio,Search,Vector,Directory,我构建了这个函数来搜索某个目录中的文件 一切正常,但当我打印向量时,向量的输出是错误的。在while循环内部,向量被正确的数据填充,但是当我在while循环外部(在下一个for循环中)输出它们时,数据不再相同 我想不出是怎么回事。有什么想法吗 void search(const fs::path& directory, const fs::path& file_name, string input, string &compFileName, string &Fp
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;
}
}
}
void搜索(常量fs::path和directory,常量fs::path和file\u name,字符串输入,字符串和compFileName,字符串和Fpath)
{
字符串t;
autod=fs::递归目录迭代器(目录);
自动查找=标准::查找if(d,end(d),[&](const auto&dir_条目)
{
Fpath=dir_entry.path().string();
t=dir_entry.path().filename().string();
返回t.find(file_name.string())!=std::string::npos;
}
);
如果(找到==结束(d))
库特
这并不是创建FPath
的副本,它只是提供指向存储实际字符串的原始内存的指针
Fpath = dir_entry.path().string();
现在,Fpath
具有不同的值,内部原始内存和存储的指针也具有不同的值
当点击t.find(file_name.string())!=std::string::npos;
时,这里也会修改Fpath
,这将被向量中所有存储的指针引用
这并不是创建FPath
的副本,它只是提供指向存储实际字符串的原始内存的指针
Fpath = dir_entry.path().string();
现在,Fpath
具有不同的值,内部原始内存和存储的指针也具有不同的值
当t.find(文件名.string())!=std::string::npos;
被命中,Fpath
在这里也被修改,这将被vector中所有存储的指针引用。您正在存储指向字符串缓冲区的指针,这些指针在每次更改源字符串时都会失效。因此,两个向量基本上都用悬空指针填充。您需要像这样存储字符串这:vector pfilesFound;
您正在存储指向字符串缓冲区的指针,这些指针在每次更改源字符串时都会失效。因此,这两个向量基本上都充满了悬空指针。您需要像这样存储字符串:vector pfilesFound;
MS typedefs…指针是指针,无论是否命名LPCSTR
或const char*
。MS typedefs…指针是指针,无论是命名为LPCSTR
还是const char*
。