[英]C++ _findfirst and TCHAR
我得到了以下代码:
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]目前给出以下错误:
错误:类型“_TCHAR *”的参数与“const char *”类型的参数不兼容
现在我用Google搜索了TCHAR,我知道它是wchar_t *或char *取决于使用Unicode字符集或多字节字符集(我目前正在使用Unicode)。 我也明白转换是一个巨大的痛苦。 所以我要问的是:我怎样才能最好地利用_TCHAR和_findfirst参数解决这个问题?
我打算将dirEntry.name连接到argv [1],并在最后连接一个“*”,并在另一个_findfirst中使用它。 我对代码的任何评论都很受欢迎,因为我还在学习C ++。
请参见此处: _findfirst用于多字节字符串,而_wfindfirst
用于宽字符。 如果在代码中使用TCHAR,则使用_tfindfirst
(宏)将解析为非UNICODE上的_findfirst,以及UNICODE构建时的_wfindfirst。
而不是_finddata_t使用_tfinddata_t,它也将根据UNICODE配置解析为正确的结构。
另一件事是你应该使用正确的文字, _T("C:/*")
在UNICODE构建时将是L"C:/*"
,否则将是"C:/*"
。 如果您知道使用UNICODE定义构建,则使用std::vector<std::wstring>
。
顺便说一句。 默认情况下,Visual Studio将使用UNICODE创建项目,您可能只使用_wfindfirst
等广泛版本的函数,因为没有充分的理由来构建非UNICODE项目。
TCHAR和我理解它是wchar_t *或char *取决于使用UTF-8字符集或多字节字符集(我目前使用的是UTF-8)。
这是错误的,在UNICODE窗口中,apis使用UTF-16。 sizeof(wchar_t)==2
。
使用这个简单的typedef
:
typedef std::basic_string<TCHAR> TCharString;
然后在使用std::string
地方使用TCharString
,例如:
vector<TCharString> dirArray;
有关std :: basic_string的信息,请参见此处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.