Reading and writing 64bits by 64 bits in C

2019-09-18 10:24发布

问题:

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

回答1:

fread(&data, 8, 1, input)

tries to read one "item" with 8 bytes into the buffer, and returns the number of items. If less than 8 bytes are left from the current position to EOF, it returns 0.

One possible solution would be to read 8 items à 1 byte instead:

ssize_t amount;
while ((amount = fread(&data, 1, 8, input)) > 0)
{
    fwrite(&data, 1, amount, output);
}

Inside the while-block you can then check if amount is 8 or less, for your encryption method.