C++ _findfirst 和 TCHAR

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] 包含我放在 "command arguments" 下的项目属性中的内容,现在它包含我想在 (C:/users/name/New 文件夹/*) 中测试我的应用程序的目录,其中包含一些带有子文件夹和一些随机文件的文件夹。 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++,因此也欢迎对我的代码提出任何意见。

使用这个简单的 typedef:

typedef std::basic_string<TCHAR> TCharString;

然后在您使用 std::string 的地方使用 TCharString,例如此处:

vector<TCharString> dirArray;

有关 std::basic_string 的信息,请参阅此处。

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

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

另一件事是您还应该使用正确的文字,_T("C:/*") 在 UNICODE 构建中将是 L"C:/*",否则是 "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 api 使用 UTF-16。 sizeof(wchar_t)==2