在反斜杠后附加 w 的 TCHAR 数组

TCHAR array appending w after backslash

本文关键字:TCHAR 数组      更新时间:2023-10-16

我正在编写一个带有多字节字符的C++ MFC应用程序,并且我正在尝试迭代运行驱动器号以检查USB连接。我的这部分代码开始在调试模式下给我带来一些问题:

for(int i = 0; i < 26; i++){
...
    //Possible device path
    TCHAR drivePath[3] = {_T('A'+i), _T(':'), _T('')};
...
}

永远不会找到驱动器,因为此数组总是在末尾附加一个"w"。

例如,对于 i=0drivePath=A:w

我的假设是它与多字节/Unicode 相关,但我假设通过使用 TCHAR_T ,它会解决这个问题。

有什么问题吗?

您从未以空字符终止数组。

TCHAR drivePath[3] = {_T('A'+i), _T(':'), _T('')};

应该是

TCHAR drivePath[4] = {_T('A'+i), _T(':'), _T(''), _T('')};
// or
TCHAR drivePath[] = {_T('A'+i), _T(':'), _T(''), _T('')};
//             ^^ let the compiler figure out the size

还有另一种选择:

TCHAR drivePath[] = { _T("A:\") };
for (char ch = 'A'; ch <= 'Z'; ch++){
    //Possible device path
    drivePath[0] = ch;
}