Unicode File Writing and Reading in C++?

落花浮王杯 提交于 2019-12-22 22:21:55

问题


Can anyone Provide a Simple Example to Read and Write in the Unicode File a Unicode Character ?


回答1:


On linux I use the iconv (link) library which is very standard. An overly simple program is:

#include <stdio.h>
#include <stdlib.h>
#include <iconv.h>

#define BUF_SZ  1024
int main( int argc, char* argv[] )
{
    char bin[BUF_SZ];
    char bout[BUF_SZ];
    char* inp;
    char* outp;
    ssize_t bytes_in;
    size_t bytes_out;
    size_t conv_res;
    if( argc != 3 )
    {
        fprintf( stderr, "usage: convert from to\n" );
        return 1;
    }
    iconv_t conv = iconv_open( argv[2], argv[1] );
    if( conv == (iconv_t)(-1) )
    {
        fprintf( stderr, "Cannot conver from %s to %s\n",  argv[1], argv[2] );
        return 1;
    }

    bytes_in = read( 0, bin, BUF_SZ );
    {
        bytes_out = BUF_SZ;
        inp = bin;
        outp = bout;
        conv_res = iconv( conv, &inp, &bytes_in, &outp, &bytes_out );
        if( conv_res >= 0 )
        {
            write( 1, bout, (size_t)(BUF_SZ) - bytes_out );
        }
    }
    iconv_close( conv );
    return 0;
}

This is overly simple to demonstrate the conversion. In the real world you would normally have two nested loops:

  • One reading input, so handle when its more than BUF_SZ
  • One converting input to output. Remember if you're converting from ascii to UTF-32LE you will end up with each iunput byte being 4 bytes of output. So the inner loop would handle this by examining conv_res and then checking errno.



回答2:


try http://utfcpp.sourceforge.net/. the link has an introductory example to read a utf8 file, line by line.




回答3:


In case you're using Windows. Use fgetws http://msdn.microsoft.com/en-us/library/c37dh6kf(VS.71).aspx to read and fputws http://msdn.microsoft.com/en-us/library/t33ya8ky(VS.71).aspx to write.

The example code are in the provided links.



来源:https://stackoverflow.com/questions/3905235/unicode-file-writing-and-reading-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!