Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class UTF16_File
- {
- std::string FILENAME;
- UFILE* INPUT;
- UFILE* open() const {
- UFILE* file = u_fopen(FILENAME.c_str(),"r",nullptr,"UTF16");
- if( ! file ) throw std::invalid_argument("File couldn't open.");
- return file;
- }
- auto get_filesize() {
- if( fseek(u_fgetfile(INPUT),0,SEEK_END) != 0 )
- throw std::runtime_error(std::strerror(errno));
- auto position = ftell(u_fgetfile(INPUT));
- if( position == -1L )
- throw std::runtime_error(std::strerror(errno));
- u_frewind(INPUT);
- return position;
- }
- UTF16_File( const std::string& filename ) : FILENAME(filename),
- INPUT(open()) { }
- ~UTF16_File() {
- u_fclose(INPUT);
- }
- std::string str() {
- // The filesize is UTF-16 so it is double the size of the string needed
- auto length = get_filesize()/2;
- // Create a storage space for the file data
- UnicodeString buffer;
- UChar* bufmem = buffer.getBuffer(length);
- if( ! bufmem )
- throw std::runtime_error(std::strerror(errno));
- // Move the data into the storage space
- int32_t bytesread = u_file_read(bufmem,length,INPUT);
- if(bytesread < length-1) throw std::runtime_error(
- "File could not be read in its entirety!");
- buffer.releaseBuffer(bytesread);
- // Create a string to receive the converted data
- std::string retval;
- return buffer.toUTF8String(retval);
- }
- friend std::string UTF16_to_UTF8(const std::string&);
- };
- std::string UTF16_to_UTF8(const std::string& filename) {
- UTF16_File u16file(filename);
- return u16file.str();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement