windows 10 c语言 unicode 读写文件的问题
我有一个UNICODE写的文件
我读取的时候
FILE* pSt_File = _tfopen(_T("D:\\1\\x64\\Debug\\1.txt"), _T("r+"));
if (NULL == pSt_File)
{
int nRet = errno;
return FALSE;
}
int nMsgLen = 1024;
TCHAR* ptszMsgBuffer = (TCHAR*)malloc(1024);
if (NULL == ptszMsgBuffer)
{
return FALSE;
}
memset(ptszMsgBuffer, '\0', 1024);
size_t nRet = fread(ptszMsgBuffer, sizeof(TCHAR), 1024, pSt_File);
fclose(pSt_File);
fread 永远返回0 ,但是我改成 fread(ptszMsgBuffer, sizeof(CHAR), 1024, pSt_File);
就正常了,为啥unicode下参数2要1个字节大小啊?
因为在 Windows 平台下,unicode 使用的是 utf16 编码,一个字符占用两个字节。你要用 unicode 编码读取文件内容的话,那么你应该使用 wchar_t 类型的缓冲区来存储读取到的数据,而不是 tchar 类型的缓冲区。
FILE* pSt_File = _wfopen(L"D:\\1\\x64\\Debug\\1.txt", L"r");
if (NULL == pSt_File)
{
int nRet = errno;
return FALSE;
}
int nMsgLen = 1024;
wchar_t* pwchMsgBuffer = (wchar_t*)malloc(nMsgLen * sizeof(wchar_t));
if (NULL == pwchMsgBuffer)
{
return FALSE;
}
memset(pwchMsgBuffer, L'\0', nMsgLen * sizeof(wchar_t));
size_t nRet = fread(pwchMsgBuffer, sizeof(wchar_t), nMsgLen - 1, pSt_File);
if (nRet == 0)
{
// 读取文件失败
fclose(pSt_File);
return FALSE;
}
// 将读取到的内容输出到控制台
wprintf(L"Read content: %ls\n", pwchMsgBuffer);
fclose(pSt_File);