I have this super simple code where I read blocks of 8 bytes (I will encrypt them later in the code) and then write them down in a new file.
It works well but for the last 8 bytes which don't get written. Any idea why?
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
int main()
{
uint64_t data;
FILE *input, *output;
// create output file
output = fopen("output.txt", "w");
// read file
input = fopen("test.txt", "rb");
if(input)
{
while(fread(&data, 8, 1, input) == 1)
{
fwrite(&data, 8, 1, output);
}
size_t amount;
while((amount = fread(&data, 1, 8, input)) > 0)
{
fwrite(&data, 1, amount, output);
}
fclose(input);
fclose(output);
}
return EXIT_SUCCESS;
}
test.txt
suggests that. Perhaps there are newlines that you are not counting, and the input file is not a multiple of 8 bytes in size. Also, you should not assume CHAR_BIT == 8 or sizeof(uint64_t) == 8 – Unconscioussizeof(uint64_t)
would be 1 if the machine has 64-bit characters. That is quite a stretch of the imagination (Crays used to have all types 32 bits for performance, but that is the weirdest I've seen). – Jilly