【问题标题】:UTF-32 to UTF-8 converter in C, buffer is full of nulls / zeroesC中的UTF-32到UTF-8转换器,缓冲区充满了空值/零
【发布时间】:2011-08-02 07:41:09
【问题描述】:

我一直在努力让它发挥作用。该程序应该采用两个参数,一个用于缓冲区大小,另一个用于文件名,并将该文件从 UTF-32 转换为 UTF-8。我一直在使用 fgetc() 函数用 Unicode 代码点填充一个 int 数组。我已经测试 printint 输出缓冲区的内容,它包含所有这些空字符而不是每个代码点。

例如,对于仅包含字符“A”的文件: 缓冲区 [0] 为 0 缓冲区 [1] 为 0 缓冲区 [2] 为 0 缓冲区 [3] 为 41

任何高于 U+7F 的代码点最终都会分开。

这是初始化我的缓冲区的代码:

int main(int argc, char** argv) {
  if (argc != 3) {
    printf("Must input a buffer size and a file name :D");
    return 0;
  }

  FILE* input = fopen(argv[2], "r");
  if (!input) {
    printf("The file %s does not exist.", argv[1]);
    return 0;
  } else {
    int bufferLimit = atoi(argv[1]);
    int buffer[bufferLimit];
    int charReplaced = 0;
    int fileEndReached = 0;
    int i = 0;
    int j = 0;

    while(1) {
      // fill the buffer with the characters from the file.
      for(i = 0; i < bufferLimit; i++){
        buffer[i] = fgetc(input);
        // if EOF reached, move onto next step and mark that
        // it has finished.
        if (buffer[i] == EOF) {
          fileEndReached = 1;
          break;
        }
      }
      // output buffer of chars until EOF or end of buffer
      for(j = 0; j <= i; j++) {
        if(buffer[j] == EOF) {
          break;
        }
        // check for Character Replacements
        charReplaced += !convert(buffer[j]);
      }
      if(fileEndReached != 0) {
        break;
      } 
    }  
    //return a 1 if any Character Replacements were used
    if(charReplaced != 0) {
      return 1;
    }
  }
}

【问题讨论】:

    标签: c unicode utf-8 fgetc utf-32


    【解决方案1】:

    fgetc() 返回一个字节,而不是一个 unicode 代码点。

    从那时起,基于这种错误的假设,整个事情都崩溃了。

    【讨论】:

    • UTF-32 每个代码点使用 4 个字节。对于每个代码单元使用超过 1 个字节的编码(UTF-16、UTF-32),您还必须考虑字节序。
    猜你喜欢
    • 2020-01-28
    • 1970-01-01
    • 2014-07-16
    • 2021-01-30
    • 2022-01-16
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    相关资源
    最近更新 更多