Advertisement
congdantoancau

Handle In/Output file

Feb 1st, 2018
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. // Source: https://cppcodetips.wordpress.com/2014/09/16/reading-and-writing-a-unicode-file-in-c/
  2.  
  3. #include <iostream>
  4. #include <fstream>
  5. #include <sstream>
  6. #include <string>
  7. #include <tchar.h>
  8. using namespace std;
  9.  
  10.  
  11. std::wstring readUnicodeFile(const char* filename)
  12. {
  13.     std::ifstream wif(filename);
  14.     std::stringstream wss;
  15.     wss << wif.rdbuf();
  16.     std::string  const &str = wss.str();
  17.     std::wstring wstr;
  18.     wstr.resize(str.size() / sizeof(wchar_t));
  19.     std::memcpy(&wstr[0], str.c_str(), str.size()); // copy data into wstring
  20.     return wstr;
  21. }
  22.  
  23. void WriteUnicodetoFile(const char* myFile, wstring& ws) {
  24.     std::ofstream outFile(myFile, std::ios::out | std::ios::binary);
  25.     outFile.write((char *)ws.c_str(), ws.length() * sizeof(wchar_t));
  26.     outFile.close();
  27.  
  28. }
  29.  
  30. int main(int argc, _TCHAR* argv[])
  31. {
  32.     wstring sText = readUnicodeFile("inputUnicode.txt");
  33.     WriteUnicodetoFile("ouputUnicode.txt", sText);
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement