【函数的三个重载形式】
void fputs_UTF8(const wchar_t *str, FILE *fp);
用于将wchar_t字符数组写入通过fopen打开的文件中。
void fputs_UTF8(const wchar_t *str, ofstream &file);
用于将wchar_t字符数组写入通过ofstream打开的文件中。
void fputs_UTF8(wstring &wstr, ofstream &file);
用于将wstring字符串对象写入通过ofstream打开的文件中。
【使用范例】
// writestr.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <Windows.h>
using namespace std;
void fputs_UTF8(const wchar_t *str, FILE *fp)
{
int size = WideCharToMultiByte(CP_UTF8, NULL, str, -1, NULL, 0, NULL, NULL);
char *buffer = (char *)malloc(size * sizeof(char));
WideCharToMultiByte(CP_UTF8, NULL, str, -1, buffer, size, NULL, NULL);
fwrite(buffer, size - sizeof(char), 1, fp);
free(buffer);
}
void fputs_UTF8(const wchar_t *str, ofstream &file)
{
int size = WideCharToMultiByte(CP_UTF8, NULL, str, -1, NULL, 0, NULL, NULL);
char *buffer = new char[size];
WideCharToMultiByte(CP_UTF8, NULL, str, -1, buffer, size, NULL, NULL);
file.write(buffer, size - 1);
delete buffer;
}
void fputs_UTF8(wstring &wstr, ofstream &file)
{
int size = WideCharToMultiByte(CP_UTF8, NULL, wstr.c_str(), -1, NULL, 0, NULL, NULL);
char *buffer = new char[size];
WideCharToMultiByte(CP_UTF8, NULL, wstr.c_str(), -1, buffer, size, NULL, NULL);
file.write(buffer, size - 1);
delete buffer;
}
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t wch[] = L"简体中文ABC";
FILE *fp;
fopen_s(&fp, "test/utf8test.txt", "w");
fputs_UTF8(wch, fp);
fclose(fp);
fopen_s(&fp, "test/utf8emptytest.txt", "w");
fputs_UTF8(L"", fp);
fclose(fp);
ofstream file("test/ofstreamutf8test.txt", ios::out);
fputs_UTF8(wch, file);
file << endl << "English letters can be directly output.";
file.close();
wstring wstr = L"这是一个C++里面的wstring字符串。";
file.open("test/ofstreamutf8test2.txt", ios::out);
fputs_UTF8(wstr, file);
file << endl << "English letters can be directly output.";
file.close();
return 0;
}
【生成的文件】
其中一个文件: