【问题标题】:Unicode File Writing and Reading in C++?用 C++ 编写和读取 Unicode 文件?
【发布时间】:2010-10-11 10:11:09
【问题描述】:

谁能提供一个在 Unicode 文件中读取和写入 Unicode 字符的简单示例?

【问题讨论】:

  • 什么格式? UTF-8、UTF-16 还是 UTF-32?
  • 如果是 UTF-16,那么 3 种可能的 UTF-16 格式中的哪一种? Big-endian、little-endian,还是由 BOM 指定?
  • 那么,在哪个平台上? wchar_t 的大小并不相同:在 Windows 上,您通常将字符串内部存储在 UTF-16 LE 中,而在 Linux 上则使用 UTF-8(char)或 UTF-32(wchar_t)。
  • UTF-16 和 32 以及 16 BOM 和平台 Windows 和 OS XP SP2

标签: c++ unicode unicode-string


【解决方案1】:

试试http://utfcpp.sourceforge.net/。该链接有一个介绍性示例,用于逐行读取 utf8 文件。

【讨论】:

    【解决方案2】:

    在 linux 上,我使用非常标准的 iconv (link) 库。一个过于简单的程序是:

    #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;
    }
    

    这对于演示转换过于简单。在现实世界中,您通常会有两个嵌套循环:

    • 一个读数输入,所以当它超过 BUF_SZ 时处理
    • 一个将输入转换为输出。请记住,如果您要从 ascii 转换为 UTF-32LE,您最终会得到每个 iunput 字节是 4 个字节的输出。因此,内部循环将通过检查 conv_res 然后检查 errno 来处理此问题。

    【讨论】:

      【解决方案3】:

      如果您使用的是 Windows。 使用 fgetws http://msdn.microsoft.com/en-us/library/c37dh6kf(VS.71).aspx 阅读 和 fputws http://msdn.microsoft.com/en-us/library/t33ya8ky(VS.71).aspx 来写。

      示例代码在提供的链接中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-27
        • 2018-02-11
        • 1970-01-01
        • 2013-09-23
        • 1970-01-01
        • 1970-01-01
        • 2014-06-17
        相关资源
        最近更新 更多