Saturday, 15 December 2018

c - Infinite loop and strange characters with: while (chars = fgetc(map) != EOF)



I'm trying to read a file (map.txt) with fopen() and fgetc(), but I'm getting an infinite loop and strange characters as output. I've tried different conditions, different possibilities, and the loop is always infinite, as if EOF did not exist.




I want to create a map-tile basic system with text files (Allegro), and to do so I need to learn how to READ them. So I'm trying to simply read the file and print its contents, character by character.



void TileSystem() {

theBitmap = al_load_bitmap("image.png"); // Ignore it.

float tileX = 0.0; // Ignore it.
float tileY = 0.0; // Ignore it.
float tileXFactor = 0.0; // Ignore it.

float tileYFactor = 0.0; // Ignore it.

al_draw_bitmap( theBitmap, 0, 0, 0 ); // Ignore it.

FILE *map;
map = fopen( "map.txt", "r");

int loopCondition = 1;
int chars;


while ( loopCondition == 1 && ( chars = fgetc( map ) != EOF ) ) {
putchar( chars );
}
}


The content of map.txt is:



1
2

3
4
5
6
7
8
9


And what I get of output is an infinite loop of:




???????????????????????????????????????????????????
???????????????????????????????????????????????????
???????????????????????????????????????????????????...


But what I see on terminal is:



EOF BUG




Well, I just need to read all the chars, and the compiler needs to recognize the end of the file correctly.


Answer



chars = fgetc( map ) != EOF


should be



(chars = fgetc(map) ) != EOF



This is a complete working example:



#include 

int main() {
FILE *fp = fopen("test.c","rt");
int c;
while ( (c=fgetc(fp))!=EOF) {
putchar(c);
}

}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...