0

当我尝试从名为“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);
    }
}
4

1 回答 1

2

问题在这里:

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

由于operator precendence,这getc(ifp) !=EOF将首先执行。然后c = <result of comparison>被执行。这不是您想要的顺序。

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

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

其他注意事项: getc返回 anint因此您应该将类​​型更改cint。此外,如果您无法打开文件,您仍然会继续执行。您应该在失败时优雅地退出。

于 2017-03-22T13:48:13.280 回答