Abh*_*nia 7 c++ wifstream clang++ wofstream
我想写一个std::wstring文件,需要读取该内容std:wstring.当字符串为时,会发生这种情况L"<Any English letter>".但是当我们有像孟加拉语,卡纳达语,日语等字符,任何类型的非英语字母时,问题就出现了.试过各种选择,如:
std::wstring为std::string写入文件并将读取时间读取为std::string转换为std::wstring
std::wstringwofstream,这对于母语字母也没有帮助 std::wstring data = L"?????? ?????????";平台是mac和Linux,语言是C++
码:
bool
write_file(
const char* path,
const std::wstring data
) {
bool status = false;
try {
std::wofstream file(path, std::ios::out|std::ios::trunc|std::ios::binary);
if (file.is_open()) {
//std::string data_str = convert_wstring_to_string(data);
file.write(data.c_str(), (std::streamsize)data.size());
file.close();
status = true;
}
} catch (...) {
std::cout<<"exception !"<<std::endl;
}
return status;
}
// Read Method
std::wstring
read_file(
const char* filename
) {
std::wifstream fhandle(filename, std::ios::in | std::ios::binary);
if (fhandle) {
std::wstring contents;
fhandle.seekg(0, std::ios::end);
contents.resize((int)fhandle.tellg());
fhandle.seekg(0, std::ios::beg);
fhandle.read(&contents[0], contents.size());
fhandle.close();
return(contents);
}
else {
return L"";
}
}
// Main
int main()
{
const char* file_path_1 = "./file_content_1.txt";
const char* file_path_2 = "./file_content_2.txt";
//std::wstring data = L"Text message to write onto the file\n"; // This is happening as expected
std::wstring data = L"?????? ?????????";
// Not happening as expected.
// Lets write some data
write_file(file_path_1, data);
// Lets read the file
std::wstring out = read_file(file_path_1);
std::wcout<<L"File Content: "<<out<<std::endl;
// Let write that same data onto the different file
write_file(file_path_2, out);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
a 的输出方式wchar_t取决于语言环境。默认区域设置 ( "C") 通常不接受除 ASCII 之外的任何内容(Unicode 代码点 0x20...0x7E,加上一些控制字符。)
任何时候程序处理文本时,第一个语句
main应该是:
std::locale::global( std::locale( "" ) );
Run Code Online (Sandbox Code Playgroud)
如果程序使用任何标准流对象,则代码还应该在任何输入或输出之前为它们注入全局语言环境。