【问题标题】:How to read unicode (utf-8) / binary file line by line如何逐行读取unicode(utf-8)/二进制文件
【发布时间】:2011-01-07 23:14:45
【问题描述】:

各位程序员,

我想逐行读取由记事本创建的 Unicode (UTF-8) 文本文件,我不想在屏幕上显示 Unicode 字符串,我只想读取和比较字符串!。

此代码逐行读取ANSI文件,并比较字符串

我想要什么

逐行读取test_ansi.txt

如果 line = "b" 打印 "YES!"

否则打印“否!”

read_ansi_line_by_line.c

#include <stdio.h>

int main()
{
    char *inname = "test_ansi.txt";
    FILE *infile;
    char line_buffer[BUFSIZ]; /* BUFSIZ is defined if you include stdio.h */
    char line_number;

    infile = fopen(inname, "r");
    if (!infile) {
        printf("\nfile '%s' not found\n", inname);
        return 0;
    }
    printf("\n%s\n\n", inname);

    line_number = 0;
    while (fgets(line_buffer, sizeof(line_buffer), infile)) {
        ++line_number;
        /* note that the newline is in the buffer */
        if (strcmp("b\n", line_buffer) == 0 ){
            printf("%d: YES!\n", line_number);
        }else{
            printf("%d: NO!\n", line_number,line_buffer);
        }
    }
    printf("\n\nTotal: %d\n", line_number);
    return 0;
}

test_ansi.txt

a
b
c

编译

gcc -o read_ansi_line_by_line read_ansi_line_by_line.c

输出

test_ansi.txt

1: NO!
2: YES!
3: NO!


Total: 3

现在我需要读取由记事本创建的 Unicode (UTF-8) 文件,6 个多月后我没有找到任何好的 C 代码/库可以读取以 UTF-8 编码的文件!,我不知道确切原因,但我认为标准 C 不支持 Unicode!

读取 Unicode 二进制文件没问题!但问题是二进制文件大多数已经以二进制模式创建!这意味着如果我们要读取由记事本创建的 Unicode (UTF-8) 文件,我们需要将其从UTF-8 文件转 BINARY 文件!

此代码将Unicode字符串写入二进制文件,注意C文件以UTF-8编码并由GCC编译

我想要什么

将 Unicode 字符“ب”写入 test_bin.dat

create_bin.c

#define UNICODE
#ifdef UNICODE
#define _UNICODE
#else
#define _MBCS
#endif

#include <stdio.h>
#include <wchar.h>

int main()
{
     /*Data to be stored in file*/
     wchar_t line_buffer[BUFSIZ]=L"ب";
     /*Opening file for writing in binary mode*/
     FILE *infile=fopen("test_bin.dat","wb");
     /*Writing data to file*/
     fwrite(line_buffer, 1, 13, infile);
     /*Closing File*/
     fclose(infile);

    return 0;
}

编译

gcc -o create_bin create_bin.c

输出

create test_bin.dat

现在我想逐行读取二进制文件并进行比较!

我想要什么

逐行读取test_bin.dat 如果 line = "ب" 打印 "YES!" 否则打印“否!”

read_bin_line_by_line.c

#define UNICODE
#ifdef UNICODE
#define _UNICODE
#else
#define _MBCS
#endif

#include <stdio.h>
#include <wchar.h>

int main()
{
    wchar_t *inname = L"test_bin.dat";
    FILE *infile;
    wchar_t line_buffer[BUFSIZ]; /* BUFSIZ is defined if you include stdio.h */

    infile = _wfopen(inname,L"rb");
    if (!infile) {
        wprintf(L"\nfile '%s' not found\n", inname);
        return 0;
    }
    wprintf(L"\n%s\n\n", inname);

    /*Reading data from file into temporary buffer*/
    while (fread(line_buffer,1,13,infile)) {
        /* note that the newline is in the buffer */
        if ( wcscmp ( L"ب" , line_buffer ) == 0 ){
             wprintf(L"YES!\n");
        }else{
             wprintf(L"NO!\n", line_buffer);
        }
    }
    /*Closing File*/
    fclose(infile);
    return 0;
}

输出

test_bin.dat

YES!

问题

这个方法很长!并且不强大(我是软件工程的初学者)

请问有人知道如何读取 Unicode 文件吗? (我知道这不容易!) 请任何人知道如何将Unicode文件转换为二进制文件? (简单方法) 请问有人知道如何以二进制模式读取Unicode文件吗? (我不确定)

谢谢。

【问题讨论】:

    标签: c windows encoding utf-8


    【解决方案1】:

    如果您使用 Visual Studio 2005 及更高版本,fgets() 可以解码 UTF-8 编码文件。像这样更改您的代码:

    infile = fopen(inname, "r, ccs=UTF-8");
    

    【讨论】:

    • nobugz 我可以在这个项目中使用 GCC/C99,有什么方法可以在 GCC 中使用您的解决方案吗? :) 谢谢 Nobugz。
    • 我对此表示怀疑,我不太了解 gcc CRT。试试看。
    • 请不要 - 您正在阻止代码在其他平台/编译器下以正确的方式运行。
    【解决方案2】:

    在本文中编写了一个编码和解码例程,并 它解释了unicode是如何编码的:

    http://www.codeguru.com/cpp/misc/misc/multi-lingualsupport/article.php/c10451/

    它可以很容易地调整为 C。 只需编码您的 ANSI 或解码 UTF-8 字符串并制作一个字节 比较

    编辑:在 OP 说从 C++ 重写函数太难之后 这里有一个模板:

    需要什么:
    + 释放分配的内存(或等待进程结束或忽略它)
    + 添加 4 字节函数
    + 告诉我 short 和 int 不保证是 2 和 4 字节长(我知道,但是 C 真的很愚蠢!)最后
    + 查找其他一些错误

    #include <stdlib.h>
    #include <string.h>
    
    #define         MASKBITS                0x3F
    #define         MASKBYTE                0x80
    #define         MASK2BYTES              0xC0
    #define         MASK3BYTES              0xE0
    #define         MASK4BYTES              0xF0
    #define         MASK5BYTES              0xF8
    #define         MASK6BYTES              0xFC
    
    char* UTF8Encode2BytesUnicode(unsigned short* input)
    {
       int size = 0,
           cindex = 0;
       while (input[size] != 0)
         size++;
       // Reserve enough place; The amount of 
       char* result = (char*) malloc(size);
       for (int i=0; i<size; i++)
       {
          // 0xxxxxxx
          if(input[i] < 0x80)
          {
             result[cindex++] = ((char) input[i]);
          }
          // 110xxxxx 10xxxxxx
          else if(input[i] < 0x800)
          {
             result[cindex++] = ((char)(MASK2BYTES | input[i] >> 6));
             result[cindex++] = ((char)(MASKBYTE | input[i] & MASKBITS));
          }
          // 1110xxxx 10xxxxxx 10xxxxxx
          else if(input[i] < 0x10000)
          {
             result[cindex++] = ((char)(MASK3BYTES | input[i] >> 12));
             result[cindex++] = ((char)(MASKBYTE | input[i] >> 6 & MASKBITS));
             result[cindex++] = ((char)(MASKBYTE | input[i] & MASKBITS));
          }
       }
    }
    
    wchar_t* UTF8Decode2BytesUnicode(char* input)
    {
      int size = strlen(input);
      wchar_t* result = (wchar_t*) malloc(size*sizeof(wchar_t));
      int rindex = 0,
          windex = 0;
      while (rindex < size)
      {
          wchar_t ch;
    
          // 1110xxxx 10xxxxxx 10xxxxxx
          if((input[rindex] & MASK3BYTES) == MASK3BYTES)
          {
             ch = ((input[rindex] & 0x0F) << 12) | (
                   (input[rindex+1] & MASKBITS) << 6)
                  | (input[rindex+2] & MASKBITS);
             rindex += 3;
          }
          // 110xxxxx 10xxxxxx
          else if((input[rindex] & MASK2BYTES) == MASK2BYTES)
          {
             ch = ((input[rindex] & 0x1F) << 6) | (input[rindex+1] & MASKBITS);
             rindex += 2;
          }
          // 0xxxxxxx
          else if(input[rindex] < MASKBYTE)
          {
             ch = input[rindex];
             rindex += 1;
          }
    
          result[windex] = ch;
       }
    }
    
    char* getUnicodeToUTF8(wchar_t* myString) {
      int size = sizeof(wchar_t);
      if (size == 1)
        return (char*) myString;
      else if (size == 2)
        return UTF8Encode2BytesUnicode((unsigned short*) myString);
      else
        return UTF8Encode4BytesUnicode((unsigned int*) myString);
    }
    

    【讨论】:

    • Thorsten S. 调整了这么长的 C++ 函数需要高级 C/C++ 程序员 xD 谢谢 Thorsten S.
    【解决方案3】:

    我知道我很糟糕......但你甚至没有考虑 BOM!这里的大多数示例都会失败。

    编辑:

    字节顺序标记是文件开头的几个字节,可以用来识别文件的编码。一些编辑添加了它们,而且很多时候它们只是以惊人的方式破坏了事情(我记得因为这个问题而与 PHP 标头问题战斗了几分钟)。

    一些 RTFM: http://en.wikipedia.org/wiki/Byte_order_mark http://blogs.msdn.com/oldnewthing/archive/2004/03/24/95235.aspx What is XML BOM and how do I detect it?

    【讨论】:

    • 唉,因为 UTF-8 是 byte 格式,所以不需要字节顺序标记。对不起,我破坏了你的坏事......
    • elcuco 你能解释一下吗? :) 谢谢 Elcuco。
    • @Thorsten S.,仅仅因为不需要字节顺序标记并不意味着你不会得到一个。我今天刚碰到一个,可能是记事本制作的。 Wikipedia 承认可以使用 UTF-8 将文件标记为 UTF-8,尽管不推荐这样做。
    • 是的,有 UTF-8 文件使用 BOM 作为标记,但许多 UTF-8 文本不使用它。我们遇到了 UTF-16 编码的问题,并将其与公司库中的 UTF-8 输出进行比较,我们发现缺少 BOM。所以我们查找了参考资料,瞧,你可以使用它,但你不需要。正如 lib 的程序员所解释的那样,BOM 会导致许多问题,因为 UTF-8 在 Internet 应用程序(邮件、usenet 等)中很猖獗,而且您不希望文本中出现奇怪的字符。我反对“这里的大多数例子都会失败”
    • 不,您需要忽略第一行的前三个字节。但前提是它们是字节 0xEF 0xBB 0xBF,按此顺序;如果不是,则说明您没有 BOM,而您使用的是整行。 (如果文件是用记事本保存的,你总是会得到一个 UTF-8 的 BOM。其他编辑器会有所不同。)
    【解决方案4】:

    UTF-8 的一个很好的特性是您不需要为了比较它而需要解码。无论您是否先解码,从 strcmp 返回的顺序都是相同的。因此,只需将其作为原始字节读取并运行 strcmp。

    【讨论】:

      【解决方案5】:

      只是为了解决 BOM 参数。这是记事本中的文件

       [paul@paul-es5 tests]$ od -t x1 /mnt/hgfs/cdrive/test.txt
       0000000 ef bb bf 61 0d 0a 62 0d 0a 63
       0000012
      

      开头有 BOM

      我个人认为不应该有 BOM(因为它是字节格式),但这不是重点

      【讨论】:

        【解决方案6】:

        我找到了我的问题的解决方案,我想将解决方案分享给任何有兴趣在 C99 中读取 UTF-8 文件的人。

        void ReadUTF8(FILE* fp)
        {
            unsigned char iobuf[255] = {0};
            while( fgets((char*)iobuf, sizeof(iobuf), fp) )
            {
                    size_t len = strlen((char *)iobuf);
                    if(len > 1 &&  iobuf[len-1] == '\n')
                        iobuf[len-1] = 0;
                    len = strlen((char *)iobuf);
                    printf("(%d) \"%s\"  ", len, iobuf);
                    if( iobuf[0] == '\n' )
                        printf("Yes\n");
                    else
                        printf("No\n");
            }
        }
        
        void ReadUTF16BE(FILE* fp)
        {
        }
        
        void ReadUTF16LE(FILE* fp)
        {
        }
        
        int main()
        {
            FILE* fp = fopen("test_utf8.txt", "r");
            if( fp != NULL)
            {
                // see http://en.wikipedia.org/wiki/Byte-order_mark for explaination of the BOM
                // encoding
                unsigned char b[3] = {0};
                fread(b,1,2, fp);
                if( b[0] == 0xEF && b[1] == 0xBB)
                {
                    fread(b,1,1,fp); // 0xBF
                    ReadUTF8(fp);
                }
                else if( b[0] == 0xFE && b[1] == 0xFF)
                {
                    ReadUTF16BE(fp);
                }
                else if( b[0] == 0 && b[1] == 0)
                {
                    fread(b,1,2,fp); 
                    if( b[0] == 0xFE && b[1] == 0xFF)
                        ReadUTF16LE(fp);
                }
                else
                {
                    // we don't know what kind of file it is, so assume its standard
                    // ascii with no BOM encoding
                    rewind(fp);
                    ReadUTF8(fp);
                }
            }        
        
            fclose(fp);
        }
        

        【讨论】:

          猜你喜欢
          • 2014-09-02
          • 2015-05-14
          • 1970-01-01
          • 1970-01-01
          • 2012-07-25
          • 1970-01-01
          • 2014-01-14
          • 1970-01-01
          • 2013-12-06
          相关资源
          最近更新 更多