0

I have a function that writes random numbers into a file while reading another file.

void writeFile() {
    FILE* file = fopen(source, "r");
    FILE* file2 = fopen(target, "w");
    srand (time(NULL));

    while (!feof(file)) {
        fgetc(file);
        fputc(0 + ( rand() % ( 50 - 0 + 1 ) ), file2);
    }


    fclose(file);
    fclose(file2);
}

The two files should have the same size. What happens is that the second file has more 1byte at the end compared with the first file. How can I avoid this?

3 Answers3

2

As well as the EOF comments, you should also open both files in binary mode

FILE* file = fopen(source, "rb");
FILE* file2 = fopen(target, "wb");

In non-binary mode line endings may be translated (depending on platform). This potentially changes the number of characters read or written to a file.

john
  • 85,011
  • 4
  • 57
  • 81
1

Don't rely on feof to tell you that you've read all characters. Instead, check the return value from fgetc:

while (fgetc(file) != EOF) {
    fputc(0 + ( rand() % ( 50 - 0 + 1 ) ), file2);
}
paddy
  • 60,864
  • 6
  • 61
  • 103
1

The very final fgetc(file) reads EOF, then your code writes a byte for it into the new file and only then it tests for feof in the while.

Don't use feof, use this instead:

if (fgetc(file) == EOF) break;
Jongware
  • 22,200
  • 8
  • 54
  • 100