senya247
senya247

Reputation: 23

fread() leaves data unread near the end of file

I'm trying to read data from a file into a buffer and write it into another file (essentially copying a file). But when i change BUFFSIZE to some bigger number, it leaves some content unread near the end of the file, meaning it does not copy the last couple of words into outfile

#define BUFFSIZE 50
int main(void)
{
    void *buffer = (void *)(malloc(BUFFSIZE));

    FILE *file = (fopen("file.txt", "r"));
    FILE *outfile = (fopen("out.txt", "w"));

    while (fread(buffer, BUFFSIZE, 1, file))
        fwrite(buffer, BUFFSIZE, 1, outfile);

    free(buffer);
    fclose(outfile);
    fclose(file);
}

It works fine when i set BUFFSIZE to 1. My file isn't that big, around 20 lines of text. Why is this happening?

Upvotes: 0

Views: 133

Answers (1)

Steve Summit
Steve Summit

Reputation: 48023

Two problems:

(1) The call

fread(buffer, BUFFSIZE, 1, file)

says you want to read up to 1 item of size 50, and it will return how many of them it read, which will be either 0 or 1. But you want

fread(buffer, 1, BUFFSIZE, file)

which will read up to 50 items (individual bytes) of size 1, and will return how many of them it read, which will be any number from 0 to 50.

See also How does fread really work?

(2) You only want to write as many bytes as fread read. So you want to capture fread's return value:

size_t r;
while ((r = fread(buffer, 1, BUFFSIZE, file)))
    fwrite(buffer, 1, r, outfile);

Upvotes: 4

Related Questions