我试图用二进制模式的ofstream写一个wstring文件,但我觉得我做错了.这就是我尝试过的:
ofstream outFile("test.txt", std::ios::out | std::ios::binary);
wstring hello = L"hello";
outFile.write((char *) hello.c_str(), hello.length() * sizeof(wchar_t));
outFile.close();
Run Code Online (Sandbox Code Playgroud)
在例如Firefox中打开test.txt,编码设置为UTF16,它将显示为:
你好
谁能告诉我为什么会这样?
编辑:
在十六进制编辑器中打开文件我得到:
FF FE 68 00 00 00 65 00 00 00 6C 00 00 00 6C 00 00 00 6F 00 00 00
Run Code Online (Sandbox Code Playgroud)
看起来我出于某种原因在每个角色之间得到两个额外的字节?
我在Linux系统上使用Qt/C++.我需要将一个QLineEdit文本转换为一个文本std::wstring并将其写入std::wofstream.它适用于ascii字符串,但是当我输入任何其他字符(阿拉伯语或乌兹别克语)时,文件中没有任何内容.(文件大小为0字节).
这是我的代码:
wofstream customersFile;
customersFile.open("./customers.txt");
std::wstring ws = lne_address_customer->text().toStdWString();
customersFile << ws << ws.length() << std::endl;
Run Code Online (Sandbox Code Playgroud)
John Smith在行编辑中输入的输出是John Smith10.但对于unicode字符串,什么都没有.
首先我认为这是一个问题QString::toStdWString(),但customersFile << ws.length();写出所有字符串的正确长度.所以我想我在写wstring文件时做错了.[?]
编辑:
我在eclipse中再次写它.并用g ++ 4.5编译它.结果是一样的:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
cout << "" << endl; // prints
wstring ws = L"????"; // this is an Arabic "Hello"
wofstream wf("new.txt");
if (!wf.bad())
wf << ws;
else
cerr << …Run Code Online (Sandbox Code Playgroud) 嗨,我有一个包含日文文本的文件,保存为unicode文件.
我需要从文件中读取并将信息显示到标准输出.
我正在使用Visual Studio 2008
int main()
{
wstring line;
wifstream myfile("D:\sample.txt"); //file containing japanese characters, saved as unicode file
//myfile.imbue(locale("Japanese_Japan"));
if(!myfile)
cout<<"While opening a file an error is encountered"<<endl;
else
cout << "File is successfully opened" << endl;
//wcout.imbue (locale("Japanese_Japan"));
while ( myfile.good() )
{
getline(myfile,line);
wcout << line << endl;
}
myfile.close();
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该程序生成一些随机输出,我在屏幕上看不到任何日文文本.