Advertisement
Guest User

Untitled

a guest
Apr 14th, 2017
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. class UTF16_File
  2. {  
  3.     std::string FILENAME;
  4.     UFILE* INPUT;
  5.    
  6.     UFILE* open() const {
  7.         UFILE* file = u_fopen(FILENAME.c_str(),"r",nullptr,"UTF16");
  8.         if( ! file ) throw std::invalid_argument("File couldn't open.");
  9.         return file;
  10.     }
  11.    
  12.     auto get_filesize() {
  13.         if( fseek(u_fgetfile(INPUT),0,SEEK_END) != 0 )
  14.             throw std::runtime_error(std::strerror(errno));
  15.         auto position = ftell(u_fgetfile(INPUT));
  16.         if( position == -1L )
  17.             throw std::runtime_error(std::strerror(errno));
  18.         u_frewind(INPUT);
  19.         return position;
  20.     }
  21.    
  22.     UTF16_File( const std::string& filename ) : FILENAME(filename),
  23.         INPUT(open()) { }
  24.    
  25.     ~UTF16_File() {
  26.         u_fclose(INPUT);
  27.     }
  28.    
  29.     std::string str() {
  30.         // The filesize is UTF-16 so it is double the size of the string needed
  31.         auto length = get_filesize()/2;
  32.        
  33.         // Create a storage space for the file data
  34.         UnicodeString buffer;
  35.         UChar* bufmem = buffer.getBuffer(length);
  36.         if( ! bufmem )
  37.             throw std::runtime_error(std::strerror(errno));
  38.        
  39.         // Move the data into the storage space
  40.         int32_t bytesread = u_file_read(bufmem,length,INPUT);
  41.         if(bytesread < length-1) throw std::runtime_error(
  42.             "File could not be read in its entirety!");
  43.         buffer.releaseBuffer(bytesread);
  44.            
  45.         // Create a string to receive the converted data
  46.         std::string retval;
  47.         return buffer.toUTF8String(retval);
  48.     }
  49.    
  50.     friend std::string UTF16_to_UTF8(const std::string&);
  51. };
  52.  
  53. std::string UTF16_to_UTF8(const std::string& filename) {
  54.     UTF16_File u16file(filename);
  55.     return u16file.str();
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement