homer512 icon

wide stream encoding errors

homer512 | PRO | 04/17/16 12:50:53 PM UTC | 0 ⭐ | 656 👁️ | Never ⏰ | []
C++ |

1.04 KB

|

None

|

0 👍

/

0 👎

#include <fstream>
// using std::ofstream, std::wifstream
#include <cstdio>
// using std::tmpnam, std::remove
#include <iostream>
// using std::wcout
#include <cerrno>
// using errno
 
int main()
{
  const char* utf8string = "foo äöü";
  /* create a temporary file with UTF8 2 byte characters.
   * Yes, I know that std::tmpnam is deprecated and none of this is really
   * portable.
   */
  char fname[L_tmpnam];
  std::tmpnam(fname);
  {
    std::ofstream out(fname, std::ios::binary);
    out << utf8string;
  }
  /**
   * Now open the file and process it with the default encoding. This should
   * fail on the first non-ASCII character
   */
  std::wifstream in(fname);
  std::wint_t inchar;
  while((inchar = in.get()) != WEOF)
    std::wcout << "Got '" << static_cast<wchar_t>(inchar) << "'\n";
  int tmp_errno = errno;
  std::wcout << "Errno == EILSEQ: " << (tmp_errno == EILSEQ)
         << "\nEOF: " << in.eof()
         << "\nFail: " << in.fail()
         << "\nBad: " << in.bad()
         << std::endl;
  std::remove(fname);
}

Comments