标准C/C++写入utf-8编码格式文件

使用Windows API处理字符格式转换

std::string ToUTF8(const wchar_t* buffer, int len)
{
	int size = ::WideCharToMultiByte(CP_UTF8, 0, buffer, len, NULL, 0, NULL,
			NULL);
	if (size == 0)
		return "";

	std::string newbuffer;
	newbuffer.resize(size);
	::WideCharToMultiByte(CP_UTF8, 0, buffer, len,
			const_cast<char*>(newbuffer.c_str()), size, NULL, NULL);

	return newbuffer;
}

std::string ToUTF8(const std::wstring& str)
{
	return ToUTF8(str.c_str(), (int) str.size());
}

使用C++写入宽字符到utf-8文件

int main()
{
    std::ofstream test_file;
    test_file.open("test.txt", std::ios::out | std::ios::binary);

    std::wstring text =
            L"中文字符";
    std::string outtext = ToUTF8(text);

    test_file << outtext;
    test_file.close();
    return 0;
}

使用C语言的方法,不过这种情况下是utf-8带有BOM

	wchar_t* data = L"中文字符";
	FILE* out_file = fopen("test.txt", "w+,ccs=UTF-8");
	fwrite(data, wcslen(data) * sizeof(wchar_t), 1, out_file);
	fclose(out_file);


你可能感兴趣的:(标准C/C++写入utf-8编码格式文件)