我正在尝试使用 WriteFile 函数将 wstring 写入 UTF-8 文件。\n我希望该文件具有这些字符“\xc3\x91\xc3\x81”,但我得到的是“\xef\xbf” \xbd"。
\n\n这是代码
\n\n#include <iostream>\n#include <cstdlib>\n#include <sstream>\n#include <string>\n#include <fstream>\n#include <windows.h>\n#include <wchar.h>\n#include <stdio.h>\n#include <winbase.h>\nusing namespace std;\n\nconst char filepath [] = "unicode.txt";\n\nint main ()\n{ \n wstring str;\n str.append(L"\xc3\x91\xc3\x81");\n wchar_t* wfilepath;\n\n // Create a file to work with Unicode and UTF-8\n ofstream fs;\n fs.open(filepath, ios::out|ios::binary);\n unsigned char smarker[3];\n smarker[0] = 0xEF;\n smarker[1] = 0xBB;\n smarker[2] = 0xBF;\n fs << smarker;\n fs.close();\n\n //Open and write in the file with windows functions\n mbstowcs(wfilepath, filepath, strlen(filepath));\n HANDLE hfile;\n hfile = CreateFileW(TEXT(wfilepath), GENERIC_WRITE, 0, NULL,\n OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n wstringbuf strBuf (str, ios_base::out|ios::app);\n DWORD bytesWritten;\n DWORD dwBytesToWrite = (DWORD) strBuf.in_avail();\n WriteFile(hfile, &strBuf, dwBytesToWrite, &bytesWritten, NULL);\n CloseHandle(hfile);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我使用以下命令行在 cygwin 上编译它:
\ng++ -std=c++11 -g Windows.C -o Windows
在将 UTF-16 数据写入文件之前,您需要将其转换为 UTF-8。
\n\n并且无需使用 创建文件std::ofstream、关闭它并使用 重新打开它CreateFileW()。只需打开文件一次并写入您需要的所有内容。
尝试这个:
\n\n#include <iostream>\n#include <cstdlib>\n#include <string>\n//#include <codecvt>\n//#include <locale>\n\n#include <windows.h>\n#include <wchar.h>\n#include <stdio.h>\n\nusing namespace std;\n\nLPCWSTR filepath = L"unicode.txt";\n\nstring to_utf8(const wstring &s)\n{\n /*\n wstring_convert<codecvt_utf8_utf16<wchar_t>> utf16conv;\n return utf16conv.to_bytes(s);\n */\n\n string utf8;\n int len = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), s.length(), NULL, 0, NULL, NULL);\n if (len > 0)\n {\n utf8.resize(len);\n WideCharToMultiByte(CP_UTF8, 0, s.c_str(), s.length(), &utf8[0], len, NULL, NULL);\n }\n return utf8;\n}\n\nint main ()\n{ \n wstring str = L"\xc3\x91\xc3\x81";\n\n // Create a UTF-8 file and write in it using Windows functions\n HANDLE hfile = CreateFileW(filepath, GENERIC_WRITE, 0, NULL,\n CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n if (hfile != INVALID_HANDLE_VALUE)\n {\n unsigned char smarker[3];\n DWORD bytesWritten;\n\n smarker[0] = 0xEF;\n smarker[1] = 0xBB;\n smarker[2] = 0xBF;\n WriteFile(hfile, smarker, 3, &bytesWritten, NULL);\n\n string strBuf = to_utf8(str);\n WriteFile(hfile, strBuf.c_str(), strBuf.size(), &bytesWritten, NULL);\n\n CloseHandle(hfile);\n }\n\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n