備忘録

備忘録

C++でShift-JIS, UTF-8, UTF-16 BOM有無とエンディアンを考慮してファイルの読み込みをする

Ⅰ. はじめに

タイトルの通り「C++でShift-JIS, UTF-8, UTF-16 BOM有無を考慮してファイルの読み込みをする」方法です。
参考のURLには重要な内容が含まれているので目を通してください。

Ⅱ. 環境

Ⅲ. プログラム

ファイルの内容を全て読み込みむサンプルです。

Shift-JIS

#include <iostream>
#include <fstream>
#include <string>

ifstream ifs("shift-jis.txt");
string str((istreambuf_iterator<char>(ifs)), istreambuf_iterator<char>());

cout << str << endl;

UTF-8 (BOM なし)

#include <iostream>
#include <fstream>
#include <string>
#include <codecvt>

setlocale(LC_ALL, "");

wifstream ifs("UTF-8N.txt");
ifs.imbue(locale(locale::empty(), new codecvt_utf8<wchar_t>));
wstring str((istreambuf_iterator<wchar_t>(ifs)), istreambuf_iterator<wchar_t>());

wcout << str << endl;

UTF-8 (BOM あり)

#include <iostream>
#include <fstream>
#include <string>
#include <codecvt>

setlocale(LC_ALL, "");

wifstream ifs("UTF-8(BOM).txt");
ifs.imbue(locale(locale::empty(), new codecvt_utf8<wchar_t, 0x10ffff, consume_header>));
wstring str((istreambuf_iterator<wchar_t>(ifs)), istreambuf_iterator<wchar_t>());

wcout << str << endl

UTF-16トルエンディアン (BOM なし)

#include <iostream>
#include <fstream>
#include <string>
#include <codecvt>

setlocale(LC_ALL, "");

wifstream ifs("UTF-16LEN.txt");
ifs.imbue(locale(locale::empty(), new codecvt_utf16<wchar_t, 0x10ffff, little_endian>));
wstring str((istreambuf_iterator<wchar_t>(ifs)), istreambuf_iterator<wchar_t>());

wcout << str << endl

UTF-16トルエンディアン (BOM あり)

#include <iostream>
#include <fstream>
#include <string>
#include <codecvt>

setlocale(LC_ALL, "");

wifstream ifs("UTF-16LE(BOM).txt");
ifs.imbue(locale(locale::empty(), new codecvt_utf16<wchar_t, 0x10ffff, consume_header>));
wstring str((istreambuf_iterator<wchar_t>(ifs)), istreambuf_iterator<wchar_t>());

wcout << str << endl;

UTF-16 ビッグエンディアン (BOM なし)

#include <iostream>
#include <fstream>
#include <string>
#include <codecvt>

setlocale(LC_ALL, "");

wifstream ifs("UTF-16BEN.txt");
ifs.imbue(locale(locale::empty(), new codecvt_utf16<wchar_t>));
wstring str((istreambuf_iterator<wchar_t>(ifs)), istreambuf_iterator<wchar_t>());

wcout << str << endl;

UTF-16 ビッグエンディアン (BOM あり)

#include <iostream>
#include <fstream>
#include <string>
#include <codecvt>

setlocale(LC_ALL, "");

wifstream ifs("UTF-16BE(BOM).txt");
ifs.imbue(locale(locale::empty(), new codecvt_utf16<wchar_t, 0x10ffff, consume_header>));
wstring str((istreambuf_iterator<wchar_t>(ifs)), istreambuf_iterator<wchar_t>());

wcout << str << endl;