Why does my inner loop only work once?

ac

#include <stdio.h> int main(int argc, char *argv[]) { int i, counter=0; char c; FILE *file=fopen("a.txt","r"); for (i = 0x41 ; i < 0x45; i++) { printf("%c(%x) ",i ,i); while ((c = fgetc(file)) != EOF) { if (i == (char) c) counter++; } printf("%d\n", counter); counter=0; } fclose(file); return 0; } 

a.txt

 AAABBBAAA 

I don’t understand why the for loop works fine, but the while runs only once.

The output looks like

enter image description here

+5
source share
3 answers

Read the man page for fgetc() , (highlighted by me)

fgetc() reads the next character from the stream and returns it as an unsigned char cast to int or EOF at the end of the file or error.

So, as soon as the while starts, it will be completed once fgetc() returns EOF , and it will return EOF for all subsequent calls.

You need to reset the file pointer to the beginning of the stream (using rewind() or fseek() ) to start from the very beginning.

Nonetheless,

  • fgetc() returns int , and char too short to retain all possible return value (e.g. EOF ). Change type c to int .
  • For hosted environments, int main() should at least have int main(void) conforming to the standard.
+7
source

The first time you run the for loop, the entire file will be exhausted, and you will never reset it. Therefore, it will only successfully search for the character 0x41 .

You need to perform one of these two operations after the while :

 fseek(file, 0, SEEK_SET); rewind(file); 

The first is preferred due to improved error handling .

+3
source

This should do the job for you:

 #include <stdio.h> int main(void) { int i, counter=0; int c; FILE *file=fopen("a.txt","r"); for (i = 0x41 ; i < 0x45; i++) { printf("%c(%x) ",i ,i); while ((c = fgetc(file)) != EOF) { if (i == c) counter++; } rewind(file); printf("%d\n", counter); counter=0; } fclose(file); return 0; } 
+3
source

Source: https://habr.com/ru/post/1259266/


All Articles