Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop while trying to read from file

I wanted to read bytes from file and then rewrite them. I did like so:

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

After executing the code on a file, the size of the file is increasing within an infinite loop.

What is the problem in my code?

like image 287
Lior Avatar asked May 24 '26 08:05

Lior


1 Answers

You are XOR-ing cCurrent with 0x10 even if it's equal to EOF. Once you XOR, it's no longer EOF, so your loop never terminates.

Make the loop infinite, and exit from the middle when you see an EOF, like this:

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);
}
like image 98
Sergey Kalinichenko Avatar answered May 25 '26 21:05

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!