homer512

wide stream encoding errors

Apr 17th, 2016
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include <fstream>
  2. // using std::ofstream, std::wifstream
  3. #include <cstdio>
  4. // using std::tmpnam, std::remove
  5. #include <iostream>
  6. // using std::wcout
  7. #include <cerrno>
  8. // using errno
  9.  
  10. int main()
  11. {
  12.   const char* utf8string = "foo äöü";
  13.   /* create a temporary file with UTF8 2 byte characters.
  14.    * Yes, I know that std::tmpnam is deprecated and none of this is really
  15.    * portable.
  16.    */
  17.   char fname[L_tmpnam];
  18.   std::tmpnam(fname);
  19.   {
  20.     std::ofstream out(fname, std::ios::binary);
  21.     out << utf8string;
  22.   }
  23.   /**
  24.    * Now open the file and process it with the default encoding. This should
  25.    * fail on the first non-ASCII character
  26.    */
  27.   std::wifstream in(fname);
  28.   std::wint_t inchar;
  29.   while((inchar = in.get()) != WEOF)
  30.     std::wcout << "Got '" << static_cast<wchar_t>(inchar) << "'\n";
  31.   int tmp_errno = errno;
  32.   std::wcout << "Errno == EILSEQ: " << (tmp_errno == EILSEQ)
  33.          << "\nEOF: " << in.eof()
  34.          << "\nFail: " << in.fail()
  35.          << "\nBad: " << in.bad()
  36.          << std::endl;
  37.   std::remove(fname);
  38. }
Add Comment
Please, Sign In to add comment