【问题标题】:How to display characters read from a file using getc()如何使用 getc() 显示从文件中读取的字符
【发布时间】:2017-03-22 13:19:00
【问题描述】:

当我尝试从名为“file1”的文件中读取输入时,我的程序正确显示 文件中的字符数,但采用无法识别的字符格式。 下面是代码

#include <stdio.h>
#include <stdlib.h>
void db_sp(FILE*);

int main(int argc,char *argv[])
{   
    FILE *ifp,*ofp;

    if(argc!=2) {
      fprintf(stderr,"Program execution form: %s infile\n",argv[0]);
      exit(1);
    }
    ifp=fopen(argv[1],"r");
    if (ifp==NULL) printf("sdaf");
    //ofp=fopen(argv[2],"w+") ; 
    db_sp(ifp);
    fclose(ifp);
    //fclose(ofp);
    return 0;
}

void db_sp(FILE *ifp)
{     
    char c;
    while(c=getc(ifp) !=EOF) {
      //printf("%c",c);
      putc(c,stdout);
      if(c=='\n' || c=='\t' || c==' ')
        printf("%c",c);
    }
}

【问题讨论】:

  • 请在您的问题中发布代码。
  • 你能显示你的文件包含什么吗?您的印刷品打印什么?

标签: c file getc


【解决方案1】:

问题出在这里:

while(c=getc(ifp) !=EOF){

因为operator precendence,这个getc(ifp) !=EOF首先被执行。然后c = &lt;result of comparison&gt; 被执行。这不是你想要的顺序。

使用括号强制执行正确的顺序。

while((c=getc(ifp)) !=EOF) {

其他说明: getc 返回一个int,因此您应该将c 的类型更改为int。 此外,如果您无法打开文件,您仍然会继续执行。您应该在失败时优雅地退出。

【讨论】:

  • 并将char c;更改为int c;,这是getc()返回的类型,putc()需要。
  • @WeatherVane 是的。已更新。
  • @AjeyaSiddhartha 对于它的价值 '\n' 也是 int 类型。
  • getc 返回 int 而不是 char 的原因是 '\xff' 是一个有效字符,不应被误解为文件的结尾。
猜你喜欢
  • 2013-07-13
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 2014-01-12
  • 2021-03-09
  • 1970-01-01
  • 2011-01-31
相关资源
最近更新 更多