尝试从文件读取时无限循环

时间:2012-11-07 14:28:08

标签: c file fopen infinite-loop

我想从文件中读取字节然后重写它们。 我确实喜欢这样:

FILE *fp;
int cCurrent;
long currentPos;

/* check if the file is openable */
if( (fp = fopen(szFileName, "r+")) != NULL )
{
    /* loop for each byte in the file crypt and rewrite */
    while(cCurrent != EOF)
    {
        /* save current position */
        currentPos = ftell(fp);
        /* get the current byte */
        cCurrent = fgetc(fp);
        /* XOR it */
        cCurrent ^= 0x10;
        /* take the position indicator back to the last position */
        fseek(fp, currentPos, SEEK_SET);
        /* set the current byte */
        fputc(cCurrent, fp);
    }

在文件上执行代码后,文件的大小在无限循环内增加。

我的代码中有什么问题?

1 个答案:

答案 0 :(得分:3)

XOR cCurrent 0x10 EOF,即使它等于XOR。一旦EOF,它就不再是EOF,所以你的循环永远不会终止。

使循环无限,当你看到for (;;) { /* save current position */ currentPos = ftell(fp); /* get the current byte */ if ((cCurrent = fgetc(fp)) == EOF) { break; } /* XOR it */ cCurrent ^= 0x10; /* take the position indicator back to the last position */ fseek(fp, currentPos, SEEK_SET); /* set the current byte */ fputc(cCurrent, fp); /* reset stream for next read operation */ fseek(fp, 0L, SEEK_CUR); } 时从中间退出,如下所示:

{{1}}