0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++のwstringをファイルに書き込む。読み込む。

Last updated at Posted at 2019-10-27

まずは免責です。

自分は仕様を完全に把握していないので場当たり的なコードを書くことがたくさんあります。

何をしたか。

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;
}

スクリーンショット

mess.png

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?