问题
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 checkingerrno
.
回答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