skk
skk

Reputation: 67

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?

Upvotes: 0

Views: 125

Answers (3)

Shivansh Pratap
Shivansh Pratap

Reputation: 1

Try Out This Code:

FILE *fp;

fp = fopen("dic.txt", "r");
int ch = getc(fp);

while(ch != EOF){
    if(getc(fp) == ' '){
        printf("up ");
    }
}

return 0;

Upvotes: 0

Stef
Stef

Reputation: 15525

You are calling getc twice per iteration of the loop; one of these two calls compares the character to EOF, while the other call compares the character to ' '.

This has two consequences:

  • Your program will only print "up" for the spaces which are on even position, and will miss all spaces which are on odd position;
  • Your program might make one extra call to getc after reaching EOF the first time.

How to fix

You need to make a single call to getc per iteration of the loop. Save the character returned by getc to a local variable; then use this variable to check for spaces in the body of the loop, and to check for EOF in the condition of the loop.

Upvotes: 3

Jabberwocky
Jabberwocky

Reputation: 50881

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 ");
    }
  }
}
  • You need to call getc once only in the loop, otherwise you skip one out of two characters.
  • Bonus: you need to check if fopen fails.

Upvotes: 0

Related Questions