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:
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