Ⅰ. はじめに
タイトルの通り「C++でShift-JIS, UTF-8, UTF-16 BOM有無を考慮してファイルの読み込みをする」方法です。
参考のURLには重要な内容が含まれているので目を通してください。
Ⅱ. 環境
- Visual Studio 2017
- Windows 10 Pro 64 bit Version 1703 (Creators Update)
Ⅲ. プログラム
ファイルの内容を全て読み込みむサンプルです。
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;