まずは免責です。
自分は仕様を完全に把握していないので場当たり的なコードを書くことがたくさんあります。
何をしたか。
std::wstringをVC2019上で読み書きするコードを書きました。文字コードは選択できるようにしてありますが、自分は詳しくないです。
なるべく汎用に書くようにしました。
余談
Windowsでアドベンチャーゲームのシステムを組もうと思ったのですが、どうしても日本語を扱わざるを得ないので、そのコードを検索して書きました。
2バイト以上の文字の扱いが解らないので2バイト固定で書くことにしたのです。
正直手抜きです。Orz
コード
Source.cpp
# include <iostream>
# include <fstream>
# include <string>
//dev on VS2019.
bool wstringSave(const std::wstring& Name, const std::wstring& In,std::string Locale="Japanese") {
std::wofstream fs(Name);
if (!fs.is_open()) return false;
auto Loc = std::locale(Locale.c_str());
auto L = fs.imbue(Loc);
fs << In << std::endl;//Write.
fs.imbue(L);//念のため
return true;
}
std::wstring wstringLoad(const std::wstring& Name,std::string Locale="Japanese") {
std::wifstream fs(Name);
if (!fs.is_open()) return {};
auto Loc = std::locale(Locale.c_str());
auto L = fs.imbue(Loc);
std::wstring Line;
std::getline(fs, Line);//read.
fs.imbue(L);//念のため
return Line;
}
int main() {
std::wstring Path = L"Hoge_Moge_Hage.txt";
std::wstring Data = L"日本語";
std::string L = "Japanese";
# if 0
std::cout<<"Write to file."<<std::endl
wstringSave(Path, Data,L);
# else
auto Loc = std::wcout.imbue(std::locale(L));
std::wcout << L"Read from File." << std::endl;
std::wstring S = wstringLoad(Path, L);
std::wcout << S << std::endl;
std::wcout.imbue(Loc);
# endif
std::wcout << L"Program End." << std::endl;
return 0;
}