Can't read whole file in c

I'm trying to move content from one file to another.
My code:

    char *path = extractFileName(args[1]);
    if (path == 0)
        return -1;
    FILE *input = fopen(path, "r");

    rewind(input);
    fseek(input, 0L, SEEK_END);
    long sz = ftell(input);
    printf("sz: %ld\n", sz);
    rewind(input);

    size_t a;
    FILE *result = fopen("result.mp3", "w");
    size_t counter = 0;
    char buffer[128];
    while ((a = fread(&buffer[0], 1, 128, input)) != 0) {
        fwrite(&buffer[0], 1, a, result);
        counter += a;
    }

    printf("%d\n", counter);
    printf("ferror input: %d\n", ferror(input));
    printf("feof input: %d\n", feof(input));

After execution it prints

sz: 6675688
25662
ferror input: 0
feof input: 16

As far as I know it means that C knows that size of input file is 665kb but returns eof when I try to read more than 25662 bytes. What I'm doing wrong?

Upvotes: 1

Views: 772

Answers (1)

Shawn
Shawn

Reputation: 52674

Since your output filename is result.mp3, it's a safe bet you're dealing with non-textual data. That means you should be opening your files in binary mode - "rb" and "wb" respectively. If you're running this code on Windows, not doing that would explain the behavior you're seeing (On that platform, reading a particular byte (0x1A) in text mode causes it to signal end of file even when it's not actually the end), and using binary mode will fix it. On other OSes, it's a no-op but still clues the reader into your intentions and the type of data you're expecting to work with, and is thus a good idea even if it's not strictly needed on them.

Upvotes: 7

Related Questions