【问题标题】:How can I read non-ascii characters from a file in C? [closed]如何从 C 文件中读取非 ascii 字符? [关闭]
【发布时间】:2014-05-07 14:56:50
【问题描述】:

我现在是这样读的:

    while (fscanf(in, "%c", infile) != EOF) 
    {
    ch = *infile;
    count++;
    ascii[ch]++;
    }

让我的频率表如下:

    void frequency ()
    {
    unsigned long long i;
    for (i = 0; i < 255; i++)
    {
     if (ascii[i] != 0)
     {
      uniqueLetters++;
      if (i < 33)
     {
    printf("=%llu\t%lu\n", i, ascii[i]);
      }
     else if (i > 126)
  {
    printf("=%llu\t%lu\n", i, ascii[i]);
  }
  else printf("%c\t%lu\n", (int)(i), ascii[i]);
}
   } 
  printf("unique letters: %lu\n", uniqueLetters);
  }

(这是一个霍夫曼编码项目,当我尝试读取整个文件时,我完全错过了 126 以上的任何内容......)

【问题讨论】:

  • 不要scanf()这太可怕了。它的使用是不直观的,它的行为中有各种微妙的错误来源。请改用fgetc()
  • 那么,您是否涉及任何不超过 127 的类型?例如char,在您的系统中可能是signed char
  • 我使用 unsigned char 因为我有 0-255 之间的任何东西
  • 不相关说明:您的代码组织可能需要一些工作。选择一种缩进样式并严格遵守它,就好像生命危在旦夕。 en.wikipedia.org/wiki/Indent_style
  • 我知道如何组织它,当我将它复制并粘贴到这个网站上时,格式变得很奇怪

标签: c file-io non-ascii-characters huffman-code


【解决方案1】:

试试fgetc:

FILE * fp = fopen(filename, "r");

int ch; // return type of fgetc is int
while ((ch = fgetc(fp)) != EOF)
    ascii[ch]++;

【讨论】:

  • 感谢您的回答,但也没有用
  • @user3366369 你有更多关于它为什么不起作用的详细信息吗?你期待什么?你看到了什么?
  • 当我从文件中读入时,我得到除了 126 以上的字符之外的所有字符......当后面有 3 个其他字符时,它以得到一个“z”结束......由于某种原因它没有'不识别大于 126 的东西
猜你喜欢
  • 1970-01-01
  • 2012-05-09
  • 2015-12-08
  • 2017-04-21
  • 2017-12-16
  • 2015-02-06
  • 2010-11-22
  • 2012-08-06
  • 2014-12-09
相关资源
最近更新 更多