WIN32_FIND_DATA 的cFileName默认是系统编码,如果有UNICODE宏(def UNICODE),api会自动把cFileName转为unicode编码,不是utf8编码,所以不加#undef _UNICODE会出现中文乱码
#ifdef _UNICODE
#undef _UNICODE
#endif // _UNICODE
#ifdef UNICODE
#undef UNICODE
#endif // _UNICODE
#include
#include
#include
int main()
{
WIN32_FIND_DATA ffd;
TCHAR szDir[MAX_PATH] = _T("D:\\aaa\\*");
HANDLE hFind = INVALID_HANDLE_VALUE;
LARGE_INTEGER filesize;
hFind = FindFirstFile(szDir, &ffd);
if (hFind == INVALID_HANDLE_VALUE)
{
printf("FindFirstFile failed (%d)\n", GetLastError());
return;
}
printf("String list........\n");
do
{
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
printf("dir:%s\n", &ffd.cFileName);
}
else
{
//如果不加#undef _UNICODE,由于cFileName是WCHAR双字节数组,小端存储缘故
//下面的printf只能打印出第一个英文字符
//printf("file:%s\n", &ffd.cFileName);
for (int i = 0; i < MAX_PATH; i++)
{
if (ffd.cFileName[i] == 0)
{
break;
}
//不加#undef _UNICODE,cFileName是WCHAR,双字节远大于127,可以看到unicode编码
if (ffd.cFileName[i] < 127)
{
printf("%c", ffd.cFileName[i]);
}
else
{
printf("%d-", ffd.cFileName[i]);
}
}
printf("\n");
}
} while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
}