This was originally for an encryption dll, but the problem occurs without the encryption as well.
wanted to be able to encrypt a file back into itself, and it was working beautifully, but I had to read the whole file into memory, close the file and reopen to write it back in. This was obviously a big memory hog.
Then I found out that you can open a file for read and write at the same time with rb+, and after a few tests, it seemed to work great, so I got to work programming it to transfer back into itself on buffer increments of BUFSIZ. As soon as it was done, I noticed with some files it would increase the filesize and corrupt the data right after position 1024 (two buffer increments through).
So now I show my code to you hoping you can help me find my problem.
Code:
#include <stdio.h>
long filesize(FILE *f)
{
long fs;
fseek(f,0L,SEEK_END);
fs = ftell(f);
fseek(f,0L,SEEK_SET);
return fs;
}
int crypto(char *fn)
{
FILE *f;
unsigned char fb[BUFSIZ]; //fileBuffer
long int fs, ts = 0L, tp; //filesize, Written Size, Written Position
size_t bs; //bufferSize
f = fopen(fn,"rb+");
if (f == NULL)
{
return 0;
}
fs = filesize(f);
do {
tp = ftell(f);
bs = fread(fb,sizeof *fb, sizeof fb, f);
//this is where the encryption would go
fseek(f,tp,SEEK_SET);
fwrite(fb, sizeof *fb, bs, f);
ts += bs;
} while ( ts < fs );
fclose(f);
return 1;
}
Originally I would repeat the loop while (bs == sizeof fb) but sometimes the last buffer would work out just right and then it would read past it and instead of bs being 0 like I would expect, it would return sizeof fb (which happens to be 512) full of 0 bytes, thus it would continue to write 0 bytes back into the file for infinite until I hard-terminated it. That prompted me to find the filesize and only read/write until it met the filesize.
Your help would be greatly appreciated.
-IsmAvatar