Search code examples
cfilegetc

How to display characters read from a file using getc()


When I try to read input from a file named "file1", my program correctly displays the number of characters in the file, but in an unrecognized character format. Below is the code

#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);
    }
}

Solution

  • The problem is here:

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

    Because of operator precendence, this getc(ifp) !=EOF gets executed first. Then c = <result of comparison> gets executed. Which is not the order you want.

    Use parentheses to force the correct order.

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

    Other notes: getc returns an int so you should change the type of c to int. Also, if you fail to open the file, you still continue execution. You should gracefully exit on failure.