gpt4 book ai didi

C++ _findfirst 和 TCHAR

转载 作者:行者123 更新时间:2023-11-30 02:31:59 26 4
gpt4 key购买 nike

我得到了以下代码:

int _tmain(int argc, _TCHAR* argv[]) {
_finddata_t dirEntry;
intptr_t dirHandle;
dirHandle = _findfirst("C:/*", &dirEntry);
int res = (int)dirHandle;
while(res != -1) {
cout << dirEntry.name << endl;
res = _findnext(dirHandle, &dirEntry);
}
_findclose(dirHandle);
cin.get();
return (0);
}

它的作用是打印给定目录 (C:) 包含的所有内容的名称。现在我必须打印出子目录(如果有的话)中所有内容的名称。到目前为止我已经知道了:

int _tmain(int argc, _TCHAR* argv[]) {
_finddata_t dirEntry;
intptr_t dirHandle;
dirHandle = _findfirst(argv[1], &dirEntry);
vector<string> dirArray;
int res = (int)dirHandle;
unsigned int attribT;
while (res != -1) {
cout << dirEntry.name << endl;
res = _findnext(dirHandle, &dirEntry);
attribT = (dirEntry.attrib >> 4) & 1; //put the fifth bit into a temporary variable
//the fifth bit of attrib says if the current object that the _finddata instance contains is a folder.
if (attribT) { //if it is indeed a folder, continue (has been tested and confirmed already)
dirArray.push_back(dirEntry.name);
cout << "Pass" << endl;
//res = _findfirst(dirEntry.name, &dirEntry); //needs to get a variable which is the dirEntry.name combined with the directory specified in argv[1].
}
}
_findclose(dirHandle);
std::cin.get();
return (0);

现在我不要求整个解决方案(我希望能够自己完成)但只有一件事我无法理解,那就是 TCHAR* argv。我知道 argv[1] 包含我在“命令参数”下放入我的项目属性的内容,现在它包含我想在 (C:/users/name/New folder/*) 中测试我的应用程序的目录,其中包含一些带有子文件夹和一些随机文件的文件夹。argv[1] 当前给出以下错误:

Error: argument of type "_TCHAR*" is incompatible with parameter of type "const char *"

现在我用谷歌搜索了 TCHAR,我知道它是 wchar_t* 还是 char*,具体取决于使用 Unicode 字符集还是多字节字符集(我目前使用的是 Unicode)。我也明白转换是一个巨大的痛苦。所以我要问的是:如何使用 _TCHAR 和 _findfirst 参数最好地解决这个问题?

我计划将 dirEntry.name 连接到 argv[1] 并在末尾连接一个“*”,并在另一个 _findfirst 中使用它。由于我仍在学习 C++,因此也欢迎对我的代码提出任何意见。

最佳答案

参见此处:_findfirst用于多字节字符串,而 _wfindfirst适用于宽字符。如果您在代码中使用 TCHAR,则使用 _tfindfirst (宏)它将在非 UNICODE 上解析为 _findfirst,在 UNICODE 构建上解析为 _wfindfirst。

此外,使用 _tfinddata_t 而不是 _finddata_t,它也将根据 UNICODE 配置解析为正确的结构。

另一件事是你也应该使用正确的文字,_T("C:/*")将是 L"C:/*"在 UNICODE 版本上,和 "C:/*"否则。如果你知道你正在构建定义的 UNICODE,那么使用 std::vector<std::wstring> .

顺便说一句。默认情况下,Visual Studio 将使用 UNICODE 创建项目,您只能使用广泛版本的函数,如 _wfindfirst因为没有充分的理由构建非 UNICODE 项目。

TCHAR and I understand it is either a wchar_t* or a char* depending on using UTF-8 character set or multi-byte character set (I'm currently using UTF-8).

这是错误的,在 UNICODE windows apis 中使用 UTF-16。 sizeof(wchar_t)==2 .

关于C++ _findfirst 和 TCHAR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36920784/

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