If the number of bytes in the file is not a multiple of 4, the last call to fread() will return 0.
size_t fread(void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream);
"Thefread
function returns the number of elements successfully read, which may be less thannmemb
if a read error or end-of-file is encountered."
The result value of fread()
should be used to detect an incomplete read and EOF. OP code, as is, will read once too often.
Also suggest using uint32_t
instead of unsigned int
for greater portability and checking `fwrite() results.
uint32_t buf1, buf2;
int cnt;
while((cnt = fread(&buf1, sizeof buf1, 1, fin)) == 1) {
buf2 = encrypt(buf1);
if (fwrite(&buf2, sizeof buf2, 1, fout) != 1) {
Handle_WriteError();
}
}