3

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

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);
    }

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

我的代码有什么问题?

4

1 回答 1

3

即使它等于 ,您也XOR正在cCurrent使用。一旦你,它就不再是,所以你的循环永远不会终止。0x10EOFXOREOF

使循环无限,并在看到 时从中间退出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);
}
于 2012-11-07T14:29:57.767 回答