c - Linux C 将文件从 `UTF-16LE` 转换为 `ASCII` 代码挂起

标签 c linux iconv

我尝试使用 iconv 将 UTF-16LE 文本文件转换为 ASCII,但由于某种原因,我的代码永远挂起,知道我做错了什么吗?

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

#define S_SIZE (1024)

#define bool int
#define true 1
#define false 0

int main(){
  iconv_t icd;
  FILE *fp_src, *fp_dst;
  char s_src[S_SIZE], s_dst[S_SIZE];
  char *p_src, *p_dst;
  size_t n_src, n_dst;

  icd = iconv_open("ASCII", "UTF-16LE");
  fp_src = fopen("utf8_test.txt", "rb");
  fp_dst = fopen("ascii_test.txt", "w");

  while(true){
    fgets(s_src, S_SIZE, fp_src);
    if (feof(fp_src))
      break;
    p_src = s_src;
    p_dst = s_dst;
    n_src = strlen(s_src);
    n_dst = S_SIZE-1;
    while(0 < n_src){
      iconv(icd, &p_src, &n_src, &p_dst, &n_dst);
    }
    *p_dst = '\0';
    fputs(s_dst, fp_dst);
  }

  fclose(fp_dst);
  fclose(fp_src);
  iconv_close(icd);

  return 0;
}

是否是因为 ASCII 文件在 EOF 中终止,而 UTF-16LE 在 WEOF 中终止?

最佳答案

好的,找到了 ICU 库的解决方案。

#include <stdio.h>
#include <stdlib.h>
#include <unicode/ustdio.h>
#include <unicode/uchar.h>

UChar* read_utf8_file(const char* filename, long* size) {
    /* open a UTF-8 file for reading */
    UFILE* f = u_fopen(filename, "r", NULL, "UTF-16LE");

    /* get the file size */
    long fsize;
    fseek(u_fgetfile(f), 0, SEEK_END);
    fsize = ftell(u_fgetfile(f));
    u_frewind(f);

    /* allocate enough memory to store the whole string plus termination */
    UChar* str = (UChar*) malloc(sizeof(UChar) * (fsize + 1));

    /* read the string into the allocated space */
    for ((*size) = 0; !u_feof(f); ++(*size)) {
        str[*size] = u_fgetc(f);
    }

    /* add NULL termination */
    str[*size] = 0;

    /* close the file resource */
    u_fclose(f);

    return str;
}

int main() {
    /* read the string and its size */
    long size;
    UChar* str = read_utf8_file("utf8_test.txt", &size);

    /* print the string size */
    //printf("String size: %ld\n\n", size);

    /* print the UTF-8 string */
    UFILE* u_stdout = u_finit(stdout, NULL, NULL);
    u_fprintf(u_stdout, "%S\n", str);
    u_fclose(u_stdout);

    /* free the allocated string */
    free(str);

    return 0;
}

关于c - Linux C 将文件从 `UTF-16LE` 转换为 `ASCII` 代码挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21881892/

相关文章:

c - 导入 CUnit 源代码

c - 如何通过使用和创建函数来计算命令行参数中的字符数

linux - 如何在 Octave 音程中演奏 A

linux - 在 Linux 中以编程方式连接到 wifi 网络

linux - Gnuplot,如何计算我的 gnuplot 脚本的矩阵输入的行和列?

c++ - Iconv 库多次安装导致错误

c++ - 如何在没有 libiconv 符号名称的情况下在 OSX 上构建 iconv 的静态库?

c - 如何将 2^63 添加到带符号的 64 位整数并将其转换为无符号的 64 位整数而不在中间使用 128 位整数

c - 将二维动态行分配给一维数组

ruby - 在 Ruby 中使用 Watir 填写文本字段时出现编码问题