【发布时间】:2015-02-19 23:02:44
【问题描述】:
我正在尝试使用 WriteFile 函数将 wstring 写入 UTF-8 文件。 我希望文件包含这些字符“ÑÁ”,但我得到了这个“�”。
这里是代码
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <string>
#include <fstream>
#include <windows.h>
#include <wchar.h>
#include <stdio.h>
#include <winbase.h>
using namespace std;
const char filepath [] = "unicode.txt";
int main ()
{
wstring str;
str.append(L"ÑÁ");
wchar_t* wfilepath;
// Create a file to work with Unicode and UTF-8
ofstream fs;
fs.open(filepath, ios::out|ios::binary);
unsigned char smarker[3];
smarker[0] = 0xEF;
smarker[1] = 0xBB;
smarker[2] = 0xBF;
fs << smarker;
fs.close();
//Open and write in the file with windows functions
mbstowcs(wfilepath, filepath, strlen(filepath));
HANDLE hfile;
hfile = CreateFileW(TEXT(wfilepath), GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
wstringbuf strBuf (str, ios_base::out|ios::app);
DWORD bytesWritten;
DWORD dwBytesToWrite = (DWORD) strBuf.in_avail();
WriteFile(hfile, &strBuf, dwBytesToWrite, &bytesWritten, NULL);
CloseHandle(hfile);
}
我在 cygwin 上使用这个命令行编译它:g++ -std=c++11 -g Windows.C -o Windows
【问题讨论】:
-
顺便说一句,您不需要使用匈牙利符号,因为 Microsoft 需要。编译器不关心标识符的拼写;只是名称符合 C++ 语言规则。
-
@ThomasMatthews:甚至 MS 都不再使用(反)匈牙利符号了。他们的 .NET 命名指南说不要使用匈牙利符号。
-
阅读 utf8everywhere.org 了解如何将内容转换为 UTF-8。