【发布时间】:2020-10-22 15:46:32
【问题描述】:
首先,我找到了这个来源来获取所有文件的路径(Unicode),它不属于我,我定义了一个字符串( string str = "test"; )并且它不可检测(cout
#include <atlstr.h>
#include <iostream>
#include <string>
#include <functional>
#include <io.h>
using namespace std;
enum enumflags {
ENUM_FILE = 1,
ENUM_DIR,
ENUM_BOTH
};
bool enumsubfiles(
const std::wstring& dir_with_back_slant, //for example: L"C:\\", L"E:\\test\\"
const std::wstring& filename, //for example: L"123.txt", L"*.exe", L"123.???"
unsigned int maxdepth, //0 means not searching subdirectories, 1 means maximum depth of subdirectories is 1,
// pass -1 to search all the subdirectories.
enumflags flags, //search files, directories, or both.
std::function<bool(const std::wstring& dir_with_back_slant, _wfinddata_t& attrib)> callback)
{
_wfinddata_t dat;
size_t hfile;
std::wstring fullname = dir_with_back_slant + filename;
std::wstring tmp;
bool ret = true;
hfile = _wfindfirst(fullname.c_str(), &dat);
if (hfile == -1)
goto a;
do {
if (!(wcscmp(L".", dat.name) && wcscmp(L"..", dat.name)))
continue;
if (((dat.attrib & _A_SUBDIR) && (!(flags & ENUM_DIR))) || ((!(dat.attrib & _A_SUBDIR)) && (!(flags & ENUM_FILE))))
continue;
ret = callback(dir_with_back_slant, dat);
if (!ret) {
_findclose(hfile);
return ret;
}
} while (_wfindnext(hfile, &dat) == 0);
_findclose(hfile);
a:
if (!maxdepth)
return ret;
tmp = dir_with_back_slant + L"*";
hfile = _wfindfirst(tmp.c_str(), &dat);
if (hfile == -1)
return ret;
do {
if (!(wcscmp(L".", dat.name) && wcscmp(L"..", dat.name)))
continue;
if (!(dat.attrib & _A_SUBDIR))
continue;
tmp = dir_with_back_slant + dat.name + L"\\";
ret = enumsubfiles(tmp, filename, maxdepth - 1, flags, callback);
if (!ret) {
_findclose(hfile);
return ret;
}
} while (_wfindnext(hfile, &dat) == 0);
_findclose(hfile);
return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
string str = "test";
enumsubfiles(L"B:\\", L"*.txt", -1, ENUM_FILE, [](const std::wstring& dir_with_back_slant, _wfinddata_t& attrib) -> bool {
wcout << dir_with_back_slant << attrib.name << '\n';
cout << str;
return true; //return true to continue, return false to abort searching.
});
return 0;
}
老实说,我从这个来源看不懂任何东西,我想在 int t_main() 的开头定义一个变量并在函数内部调用它 而且我不想在函数中定义它
【问题讨论】:
-
为什么会出现?它在一个不相关的范围内。您的意思是使用 lambda 捕获 吗?您应该将问题缩小到小问题。
-
如果您想在 lambda 中访问
str,您需要捕获它或将其作为参数传递。 -
如何捕获或路径呢?我试图找到它,但我做不到
-
我不知道你所说的“路径它”是什么意思,但捕获只是
[str](...){...}
标签: c++