cgetc

In C, "getc" reads only three lines from text file


My Code is HERE

int main(){
  FILE *fp;
  fp = fopen("dic.txt", "r");
  while(getc(fp) != EOF){
    if(getc(fp) == ' '){
        printf("up ");
    }
  }
}

My dic.txt is HERE

dic.txt

my predict is that "up up up up "
because, there are four space " "

but it printed "up " only one

what is problem?


Solution

  • You want this:

    #include <stdio.h>
    
    int main() {
      FILE* fp;
      fp = fopen("dic.txt", "r");
      if (fp == NULL)
      {
        printf("Can't open file\n");
        return 1;
      }
    
      int ch;                            // int is needed her, not char !!
      while ((ch = getc(fp)) != EOF) {   // read one char and check if it's EOF in one go
        if (ch == ' ') {
          printf("up ");
        }
      }
    }