メインコンテンツへスキップ
見出し画像

【C++㉛】Windowsのテキストファイルのエンコーディングについて

    レガシーな私にとって、WindowsのテキストファイルといえばShift-JISだけ考えていれば良かったのでした。
    私は、Visual C++6.0からMFCを使用してWindowsアプリケーションを作成してきましたが、何にも悩まずに、テキストファイルをCStdioFileのテキストモードで読み書きしてました。
    でも、Windows10以降の「メモ帳」ではBOMなしUTF-8がデフォルトになってしまいました。
    私のレガシープログラムでBOMなしUTF-8のテキストファイルを入力したら文字化け必至です。

    入力ファイルがUTF-8と分かっていれば、以下のコードで、入力ファイルのBOMの有無に関わらず正しく読み込めます。出力ファイルはShift-JISになります。

    
    // 入力:UTF-8
    FILE* fin = _tfopen(inPath, _T("rt, ccs=UTF-8"));
    if (!fin)
    {
        // 入力ファイルを開けない場合の処理
        return;
    }
    CStdioFile inFile(fin);
    
    // 出力:Shift-JIS
    FILE* fout = _tfopen(outPath, _T("wt"));
    if (!fout)
    {
        inFile.Close();
        // 出力ファイルを開けない場合の処理
        return;
    }
    
    CStdioFile outFile(fout);
    
    CString line;
    while (inFile.ReadString(line))
    {
        line.Insert(0, _T("@"));
        outFile.WriteString(line);
        outFile.WriteString(_T("\n"));  // 改行
    }
    
    inFile.Close();
    outFile.Close();
    

    出力ファイルをBOM付きUTF-8にしたければ以下のようになります。

    // 入力:UTF-8
    FILE* fin = _tfopen(inPath, _T("rt, ccs=UTF-8"));
    if (!fin)
    {
        // 入力ファイルを開けない場合の処理
        return;
    }
    CStdioFile inFile(fin);
    
    // 出力:UTF-8(BOM付き)で作成
    FILE* fout = _tfopen(outPath, _T("wt, ccs=UTF-8"));
    if (!fout)
    {
        inFile.Close();
        // 出力ファイルを開けない場合の処理
        return;
    }
    
    CStdioFile outFile(fout);
    
    CString line;
    while (inFile.ReadString(line))
    {
        line.Insert(0, _T("@"));
        outFile.WriteString(line);
        outFile.WriteString(_T("\n"));  // 改行
    }
    
    inFile.Close();
    outFile.Close();
    

    ですが、BOM無しUTF-8とShift-JISなのかは自動判定できないのです。
    また、BOM無しUTF-8で出力するだけでも、バイナリモードで開き、毎行を WideCharToMultiByte(CP_UTF8) で変換して書き込む必要が出てきます。

    ということで、単純に入力テキストファイルを行単位で読み込んで、先頭に"@"を付けて、入力テキストファイルと全く同じエンコーディング形式で出力するコード例を以下に示します。
    Shift-JIS、UTF-8、UTF-16LE(リトルエンディアン)、UTF-16BE(ビッグエンディアン)に対応させました。

    // PreserveEncoding_Simplified.cpp
    // 前提: UNICODEビルド / Windows 11 / ASCIIのみはCP932(Shift-JIS)扱い
    // 入力のエンコード(UTF-8/UTF-16LE/UTF-16BE/ANSI=CP932)・BOM有無・改行種別を保持しつつ、
    // 各行先頭に'@'を付加して即時出力。
    
    #include <windows.h>
    #include <tchar.h>
    #include <afxstr.h>   // MFC CString
    #include <cstdio>
    #include <vector>
    #include <string>
    
    enum class Encoding { UTF8, UTF16LE, UTF16BE, ANSI };
    enum class EOL { NONE, LF, CR, CRLF };
    
    struct EncInfo { Encoding enc; bool hasBOM; };
    
    // --- UTF-8妥当性(非ASCIIを含み、overlong/不正なし)
    static bool IsLikelyUTF8(const unsigned char* s, size_t n)
    {
        bool sawMultibyte = false;
        for (size_t i = 0; i < n;)
        {
            unsigned char c = s[i];
            if (c <= 0x7F) { i++; continue; }
            sawMultibyte = true;
            if ((c >> 5) == 0x6)
            {
                // 2-byte
                if (i + 1 >= n) break;
                unsigned char c1 = s[i+1];
                if ((c1 >> 6) != 0x2) return false;
                unsigned int code = ((c & 0x1F) << 6) | (c1 & 0x3F);
                if (code < 0x80) return false; // overlong
                i += 2;
            }
            else if ((c >> 4) == 0xE)
            {
                // 3-byte
                if (i + 2 >= n) break;
                unsigned char c1 = s[i+1], c2 = s[i+2];
                if ((c1 >> 6) != 0x2 || (c2 >> 6) != 0x2) return false;
                unsigned int code = ((c & 0x0F) << 12) | ((c1 & 0x3F) << 6) | (c2 & 0x3F);
                if (code < 0x800) return false; // overlong
                if (code >= 0xD800 && code <= 0xDFFF) return false; // surrogate禁止
                i += 3;
            }
            else if ((c >> 3) == 0x1E)
            {
                // 4-byte
                if (i + 3 >= n) break;
                unsigned char c1 = s[i+1], c2 = s[i+2], c3 = s[i+3];
                if ((c1 >> 6) != 0x2 || (c2 >> 6) != 0x2 || (c3 >> 6) != 0x2) return false;
                unsigned int code = ((c & 0x07) << 18) | ((c1 & 0x3F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F);
                if (code < 0x10000 || code > 0x10FFFF) return false;
                i += 4;
            }
            else
                return false;
        }
        return sawMultibyte;
    }
    
    // --- 先頭BOM+UTF-8妥当性に基づく判定(ASCIIのみはANSI=CP932扱い)
    static EncInfo Detect(FILE* fp, size_t sampleBytes /*例:64KB*/, bool treatASCIIAsANSI /*今回はtrue*/)
    {
        EncInfo info{Encoding::ANSI, false};
        long start = ftell(fp);
        if (start < 0) start = 0;
    
        unsigned char b[3] = {0,0,0};
        size_t r = fread(b,1,3,fp);
        if (r >= 2)
        {
            if (b[0]==0xFF && b[1]==0xFE) { info.enc = Encoding::UTF16LE; info.hasBOM = true; }
            else if (b[0]==0xFE && b[1]==0xFF) { info.enc = Encoding::UTF16BE; info.hasBOM = true; }
        }
        if (!info.hasBOM && r==3 && b[0]==0xEF && b[1]==0xBB && b[2]==0xBF)
        {
            info.enc = Encoding::UTF8; info.hasBOM = true;
        }
        // 読み位置をBOM長だけスキップ
        fseek(fp, start + (info.hasBOM ? ((info.enc==Encoding::UTF8)?3:2) : 0), SEEK_SET);
    
        if (!info.hasBOM)
        {
            std::vector<unsigned char> buf(sampleBytes);
            size_t got = fread(buf.data(),1,buf.size(),fp);
            fseek(fp, start, SEEK_SET);
            bool looksUTF8 = (got>0) && IsLikelyUTF8(buf.data(), got);
            info.enc = looksUTF8 ? Encoding::UTF8 : Encoding::ANSI;
            info.hasBOM = false;
            if (!looksUTF8 && !treatASCIIAsANSI) { info.enc = Encoding::UTF8; }
        }
        return info;
    }
    
    static CString WFromBytes(const std::vector<unsigned char>& bytes, Encoding enc, UINT ansiCP /*CP932*/)
    {
        CString out;
        if (bytes.empty()) return out;
        int wlen = 0;
        if (enc == Encoding::UTF8)
        {
            wlen = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS,
                                       reinterpret_cast<const char*>(bytes.data()), (int)bytes.size(),
                                       nullptr, 0);
        }
        else if (enc == Encoding::ANSI)
        {
            wlen = MultiByteToWideChar(ansiCP, 0,
                                       reinterpret_cast<const char*>(bytes.data()), (int)bytes.size(),
                                       nullptr, 0);
        }
        else
        {
            // UTF-16 は別経路(下で)
        }
        if (enc == Encoding::UTF8 || enc == Encoding::ANSI)
        {
            if (wlen > 0)
            {
                std::wstring w; w.resize(wlen);
                MultiByteToWideChar((enc==Encoding::UTF8)?CP_UTF8:ansiCP, (enc==Encoding::UTF8)?MB_ERR_INVALID_CHARS:0,
                                    reinterpret_cast<const char*>(bytes.data()), (int)bytes.size(),
                                    &w[0], wlen);
                out = CString(w.c_str());
            }
            return out;
        }
        return out; // UTF-16は別ルート
    }
    
    struct LineReader
    {
        FILE* fp;
        EncInfo info;
        UINT ansiCP;
        bool hasPushByte=false; int pb=0;
        bool hasPushW=false; wchar_t pw=0;
    
        LineReader(FILE* f, EncInfo i, UINT cp): fp(f), info(i), ansiCP(cp) {}
    
        bool Read(CString& line, EOL& eol)
        {
            line.Empty(); eol = EOL::NONE;
            if (info.enc == Encoding::UTF8 || info.enc == Encoding::ANSI)
            {
                std::vector<unsigned char> bytes;
                while (true)
                {
                    int ch = hasPushByte ? (hasPushByte=false, pb) : fgetc(fp);
                    if (ch == EOF) { if (bytes.empty()) return false; break; }
                    if (ch == '\r')
                    {
                        int ch2 = fgetc(fp);
                        if (ch2 == '\n') eol = EOL::CRLF;
                        else { eol = EOL::CR; hasPushByte=true; pb=ch2; }
                        break;
                    }
                    if (ch == '\n') { eol = EOL::LF; break; }
                    bytes.push_back(static_cast<unsigned char>(ch));
                }
                line = WFromBytes(bytes, info.enc, ansiCP);
                return true;
            }
            else
            {
                // UTF-16LE/BE
                std::vector<wchar_t> wbuf;
                while (true)
                {
                    wchar_t wch;
                    if (hasPushW) { wch = pw; hasPushW=false; }
                    else
                    {
                        int b1 = fgetc(fp); if (b1==EOF) { if (wbuf.empty()) return false; break; }
                        int b2 = fgetc(fp); if (b2==EOF) { break; }
                        if (info.enc == Encoding::UTF16LE)
                            wch = static_cast<wchar_t>(((unsigned char)b2<<8) | (unsigned char)b1);
                        else
                            wch = static_cast<wchar_t>(((unsigned char)b1<<8) | (unsigned char)b2);
                    }
                    if (wch == L'\r')
                    {
                        int b1 = fgetc(fp); if (b1==EOF) { eol=EOL::CR; break; }
                        int b2 = fgetc(fp); if (b2==EOF) { eol=EOL::CR; break; }
                        wchar_t next = (info.enc==Encoding::UTF16LE)
                            ? static_cast<wchar_t>(((unsigned char)b2<<8)|(unsigned char)b1)
                            : static_cast<wchar_t>(((unsigned char)b1<<8)|(unsigned char)b2);
                        if (next == L'\n') eol = EOL::CRLF;
                        else { eol=EOL::CR; hasPushW=true; pw=next; }
                        break;
                    }
                    if (wch == L'\n') { eol = EOL::LF; break; }
                    wbuf.push_back(wch);
                }
                std::wstring w(wbuf.begin(), wbuf.end());
                line = CString(w.c_str());
                return true;
            }
        }
    };
    
    static bool PutUTF16BE(FILE* fp, wchar_t wc)
    {
        unsigned char b[2] = { (unsigned char)((wc>>8)&0xFF), (unsigned char)(wc&0xFF) };
        return fwrite(b,1,2,fp) == 2;
    }
    
    struct LineWriter
    {
        FILE* fp; EncInfo info; UINT ansiCP; bool header=false;
        LineWriter(FILE* f, EncInfo i, UINT cp): fp(f), info(i), ansiCP(cp) {}
    
        bool WriteBOMIfNeeded()
        {
            if (header) return true;
            header = true;
            if (info.hasBOM)
            {
                if (info.enc == Encoding::UTF8)
                {
                    const unsigned char bom[3] = {0xEF,0xBB,0xBF};
                    if (fwrite(bom,1,3,fp)!=3) return false;
                }
                else if (info.enc == Encoding::UTF16LE)
                {
                    const unsigned char bom[2] = {0xFF,0xFE};
                    if (fwrite(bom,1,2,fp)!=2) return false;
                }
                else if (info.enc == Encoding::UTF16BE)
                {
                    const unsigned char bom[2] = {0xFE,0xFF};
                    if (fwrite(bom,1,2,fp)!=2) return false;
                }
            }
            return true;
        }
    
        bool Write(const CString& line, EOL eol)
        {
            if (!WriteBOMIfNeeded()) return false;
            std::wstring w(line.GetString());
    
            if (info.enc == Encoding::UTF8)
            {
                int len = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(), nullptr, 0, nullptr, nullptr);
                std::vector<unsigned char> out(len); if (len>0)
                    WideCharToMultiByte(CP_UTF8, 0, w.c_str(), (int)w.size(), reinterpret_cast<char*>(out.data()), len, nullptr, nullptr);
                if (!out.empty() && fwrite(out.data(),1,out.size(),fp)!=out.size()) return false;
            }
            else if (info.enc == Encoding::ANSI)
            {
                int len = WideCharToMultiByte(ansiCP, WC_NO_BEST_FIT_CHARS, w.c_str(), (int)w.size(), nullptr, 0, "?", nullptr);
                std::vector<unsigned char> out(len); if (len>0)
                    WideCharToMultiByte(ansiCP, WC_NO_BEST_FIT_CHARS, w.c_str(), (int)w.size(), reinterpret_cast<char*>(out.data()), len, "?", nullptr);
                if (!out.empty() && fwrite(out.data(),1,out.size(),fp)!=out.size()) return false;
            }
            else if (info.enc == Encoding::UTF16LE)
            {
                const unsigned char* p = reinterpret_cast<const unsigned char*>(w.data());
                size_t bytes = w.size()*sizeof(wchar_t);
                if (bytes>0 && fwrite(p,1,bytes,fp)!=bytes) return false;
            }
            else
            {
                for (wchar_t wc : w) if (!PutUTF16BE(fp, wc)) return false;
            }
    
            // 改行を入力と同じで出力(バイナリで明示)
            if (eol == EOL::CRLF) { unsigned char b[2]={'\r','\n'}; if (fwrite(b,1,2,fp)!=2) return false; }
            else if (eol == EOL::CR) { unsigned char b='\r'; if (fwrite(&b,1,1,fp)!=1) return false; }
            else if (eol == EOL::LF) { unsigned char b='\n'; if (fwrite(&b,1,1,fp)!=1) return false; }
    
            return true;
        }
    };
    
    bool ProcessPreserve(const TCHAR* inPath, const TCHAR* outPath,
                         UINT ansiCP /*CP932*/ = 932,
                         size_t sampleBytes = 65536 /*64KB*/)
    {
        FILE* fIn = _tfopen(inPath, _T("rb")); if (!fIn) return false;
        EncInfo info = Detect(fIn, sampleBytes, /*treatASCIIAsANSI*/true);
    
        FILE* fOut = _tfopen(outPath, _T("wb")); if (!fOut) { fclose(fIn); return false; }
    
        LineReader reader(fIn, info, ansiCP);
        LineWriter writer(fOut, info, ansiCP);
        if (!writer.WriteBOMIfNeeded()) { fclose(fIn); fclose(fOut); return false; }
    
        CString line; EOL eol;
        while (reader.Read(line, eol)) {
            line.Insert(0, _T("@")); // 各行先頭に '@'
            if (!writer.Write(line, eol)) { fclose(fIn); fclose(fOut); return false; }
        }
        fclose(fIn); fclose(fOut);
        return true;
    }
    
    // MFC 使用例(UNICODE)
    {
        // 入力ファイル選択
        CFileDialog dlgIn(TRUE, _T("txt"), nullptr,
            OFN_FILEMUSTEXIST | OFN_HIDEREADONLY,
            _T("テキストファイル (*.txt)|*.txt|すべてのファイル (*.*)|*.*||"), this);
        if (dlgIn.DoModal() != IDOK) return;
    
        // 出力ファイル選択
        CFileDialog dlgOut(FALSE, _T("txt"), nullptr,
            OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
            _T("テキストファイル (*.txt)|*.txt|すべてのファイル (*.*)|*.*||"), this);
        if (dlgOut.DoModal() != IDOK) return;
    
        CString inPath  = dlgIn.GetPathName();
        CString outPath = dlgOut.GetPathName();
    
        AfxMessageBox(_T("処理を開始します。入力のエンコード/EOL/BOMを保持して各行先頭に '@' を付加します。"));
    
        const BOOL ok = ProcessPreserve(inPath, outPath, /*ansiCP*/932, /*sampleBytes*/65536) ? TRUE : FALSE;
        if (ok)
        {
            CString msg; msg.Format(_T("成功: \n入力: %s\n出力: %s"), inPath.GetString(), outPath.GetString());
            AfxMessageBox(msg);
        }
        else
        {
            CString msg; msg.Format(_T("失敗: \n入力: %s\n出力: %s"), inPath.GetString(), outPath.GetString());
            AfxMessageBox(msg, MB_ICONERROR);
        }
    }
    

    ・
    ・
    ・

    どうでしょうか?
    信じられないくらい複雑になってしまいました。
    こんなシンプル仕様なのに、C++、それもMFCで文字列のエンコーディングを真面目に扱おうとすると、どうしても MultiByteToWideChar やバイナリレベルのシーク操作が避けられず、コードが肥大化してしまいます。
    かつての CStdioFile はシンプルさが売りでしたが、現代の多言語環境においては、もはや「テキストモード」という抽象化自体に無理があるのかもしれません。


     
     
    社会の底辺のその片隅で社会に絶望しているシニア(還暦)です。 いまだにスマホを持ったことのない絶滅危惧種です。 レガシーでマイノリティーな無能なモブです。 シニアの口コミを見て、このままじゃいけないと思って、とにかく何か発信することにしました。

    あなたへのおすすめ