fgets只读取第一行文件

时间:2016-04-20 06:38:49

标签: c++ c fgets fclose

我正在尝试从.cpp文件中读取文件。我正在使用C库,所以不要混淆。

所以问题就像我在标题中所说的那样清晰。 fgets方法可以读取第一行,但是当它到达第二行时,它既不能读取第二行也不读取文件的其余部分(因为它在出现问题时退出)。

您可以找到相关的代码部分:

public static float draw(Batch batch, Animation animation, float animationState,
        float delta,
        int posX, int posY, boolean flip) {
    animationState += delta;
    TextureRegion r = animation.getKeyFrame(animationState, true);
    float width = r.getRegionWidth() * SCALE;
    float height = r.getRegionHeight() * SCALE;

    if (flip) {
        batch.draw(r, posX + width, posY, -width, height);
    } else {
        batch.draw(r, posX, posY, width, height);
    }

    return animationState;
}

2 个答案:

答案 0 :(得分:6)

我相信问题存在,因为你在循环中使用了fclose(fp);。因此,在第一次迭代之后,fp将传递给fclose(),并且在任何进一步的迭代中任何重复使用fp都会调用undefined behavior作为fp <不再是有效

解决方案:将fclose(fp);移到循环外。

答案 1 :(得分:3)

您正在循环关闭文件!将fclose函数放在循环之外。

for (i = 0; i<2; i++)
{
    ....
    printf("%d\t%s\n", i, line);
    fclose(fp); // <-- here, move out of the loop.
}