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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With