Reading a UTF-16 CSV file by char

淺唱寂寞╮ 提交于 2019-12-06 14:48:15

You should use fgetwc. The below code should work in the presence of a byte-order mark, and an available locale named en_US.UTF-16.

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

main() {
  setlocale(LC_ALL, "en_US.UTF-16"); 

  FILE *fp = fopen("x.csv", "rb");
  if (fp) {
    int order = fgetc(fp) == 0xFE;
    order = fgetc(fp) == 0xFF;

    wint_t ch;
    while ((ch = fgetwc(fp)) != WEOF) {
      putchar(order ? ch >> 8 : ch);
    }
    putchar('\n');

    fclose(fp);
    return 0;
  } else {
    perror("opening x.csv");
    return 1;
  }
}

This is my solution thanks to the comments under my original question. Since every character in the CSV file is valid ascii the solution was simple as this:

int main(void)
{
    FILE *fp;
    int ch, i = 1;
    if(!(fp = fopen("x.csv", "r"))) return 1;
    while(ch != EOF)
    {
        ch = fgetc(fp);
        if(i % 2) //ch is valid ascii
        i++;
    }
    fclose(fp);

    return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!