首页 文章

无限循环和奇怪的字符:while(chars = fgetc(map)!= EOF)

提问于
浏览
1

我正在尝试使用fopen()和fgetc()读取文件(map.txt),但我得到一个无限循环和奇怪的字符作为输出 . 我尝试过不同的条件,不同的可能性,循环总是无限的,就好像EOF不存在一样 .

我想用文本文件(Allegro)创建一个map-tile基本系统,为此我需要学习如何阅读它们 . 所以我试着简单地读取文件并逐个字符地打印它的内容 .

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

我得到的输出是一个无限循环:

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

但我在终端上看到的是:

EOF BUG

好吧,我只需要读取所有字符,编译器需要正确识别文件的结尾 .

4 回答

  • 1
    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);
      }
    }
    
  • 3
    chars = fgetc( map ) != EOF )
    

    != 的优先级高于 = .

  • 1

    这一行:

    chars = fgetc( map ) != EOF
    

    正在执行这样的事情:

    chars = (fgetc( map ) != EOF)
    

    所以你应该像这样添加括号:

    (chars = fgetc( map )) != EOF
    
  • 1
    while ( loopCondition == 1 && ( chars = fgetc( map ) != EOF ) ) {
    

    看起来不对...你试过:

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

相关问题