0
Follow
0
View

Problems with Unicode reading and writing files in vs2022 c

dydtk521 注册会员
2023-02-27 17:45

Because on Windows, unicode uses utf16 encoding, where one character takes two bytes. If you want to read a file in unicode, you should use a wchar_t buffer instead of a tchar buffer to store the read data.

FILE* 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);


About the Author

Question Info

Publish Time
2023-02-27 17:45
Update Time
2023-02-27 17:45