解决WritePrivateProfileString写中文字符乱码问题

发布时间 2023-11-30 10:46:29作者: 快雪

使用WritePrivateProfileString写ini文件,在中文操作系统下写中文,没有问题,在俄文操作系统下,中文乱码。由于工程是Unicode,因此实际调用的是WritePrivateProfileStringW,而非WritePrivateProfileStringA。但是查看ini文件,发现是ANSI编码。

查阅MSDN,发现有一句话:

If the file was created using Unicode characters, the function writes Unicode characters to the file. Otherwise, the function writes ANSI characters.

看了半天没太明白,因为调用WritePrivateProfileString时会自动创建文件,而传入文件的参数都是宽字符的,理论上应该是Unicode编码。请教了一下同事,他查了一会儿,发给我一个链接,里面提到先要手动创建文件,然后写BOM,之后再调用WritePrivateProfileString,就不会出现乱码。于是,在使用WritePrivateProfileString前加了一段这样的代码:

    WORD wBOM = 0xFEFF;
    DWORD NumberOfBytesWritten;
    DeleteFile(strConfigFilePath.c_str());
    HANDLE hFile = ::CreateFile(strConfigFilePath.c_str(), GENERIC_WRITE, 0,
        NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
    ::WriteFile(hFile, &wBOM, sizeof(WORD), &NumberOfBytesWritten, NULL);
    ::CloseHandle(hFile);

问题解决了。

参考:

【1】https://www.codeproject.com/Articles/9071/Using-Unicode-in-INI-files