Skip to content

Instantly share code, notes, and snippets.

@DarrenKwonDev
Forked from leafbird/fstream_utf8.cpp
Created February 16, 2024 00:21
Show Gist options
  • Select an option

  • Save DarrenKwonDev/e0c68582cfd4bfe43d07df7ac0f90b58 to your computer and use it in GitHub Desktop.

Select an option

Save DarrenKwonDev/e0c68582cfd4bfe43d07df7ac0f90b58 to your computer and use it in GitHub Desktop.

Revisions

  1. @leafbird leafbird created this gist Jun 25, 2013.
    22 changes: 22 additions & 0 deletions fstream_utf8.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    #include <fstream>
    #include <iostream>
    #include <string>
    #include <locale>
    #include <codecvt>
    ...

    // Write file in UTF-8
    std::wofstream wof;
    wof.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t,0x10ffff,std::generate_header>));
    wof.open(L"file.txt");
    wof << L"This is a test.";
    wof << L"This is another test.";
    wof << L"\nThis is the final test.\n";
    wof.close();

    // Read file in UTF-8
    std::wifstream wif(L"file.txt");
    wif.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t,0x10ffff, std::consume_header>));

    std::wstringstream wss;
    wss << wif.rdbuf();