我正在尝试使用 fopen() 和 fgetc() 读取文件 (map.txt),但我得到了一个无限循环和奇怪的字符作为输出。我试过不同的条件,不同的可能性,循环总是无限的,就好像 EOF 不存在一样。
我想创建一个带有文本文件 (Allegro) 的 map 瓦片基本系统,为此我需要学习如何阅读它们。所以我试图简单地读取文件并逐个字符地打印其内容。
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 );
}
}
map.txt的内容是:
1
2
3
4
5
6
7
8
9
我得到的输出是一个无限循环:
???????????????????????????????????????????????????
???????????????????????????????????????????????????
???????????????????????????????????????????????????...
但我在终端上看到的是:
好吧,我只需要读取所有字符,编译器需要正确识别文件结尾。
最佳答案
chars = fgetc( map ) != EOF
应该是
(chars = fgetc(map) ) != EOF
这是一个完整的工作示例:
#include <stdio.h>
int main() {
FILE *fp = fopen("test.c","rt");
int c;
while ( (c=fgetc(fp))!=EOF) {
putchar(c);
}
}
关于c - 无限循环和带有 : while (chars = fgetc(map) ! = EOF 的奇怪字符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14552619/