Skip to content
Advertisement

Why compiled code creates corrupted file in windows in linux works fine [closed]

The following code, compiled with gcc.exe from MinGW-w64 (i686-7.1.0-posix-dwarf-rt_v5-rev0) under windows using gcc -o copy.exe copy.c creates garbage files when used to copy a file; with either to many or far too little bytes copied. Under Linux with gcc it works fine (source and destination have identical md5, text files, binary files, doesn’t matter)

#include <stdio.h>
int main(int argc, char *argv[]) {
    FILE *fp = fopen(argv[1], "rb");
    FILE *fpo = fopen(argv[2], "w");
    int SIZE = 1000000;
    char buffer[SIZE];
    size_t bytes;
    while (0 < (bytes = fread(buffer, 1, SIZE, fp)))
        fwrite(buffer, 1, bytes, fpo);
    fclose(fp);
    fclose(fpo);
    return(0);
}

Advertisement

Answer

The problem is that you read in binary data, but then you attempt to write that data out as text, as indicated in the modes you chose to do this:

FILE *fp = fopen(argv[1], "rb");
FILE *fpo = fopen(argv[2], "w");

This will cause issues on Windows and potentially other OSs, because line endings are handled differently by different standard libraries. Windows uses rn as a line ending, which is converted to n when read in from a text file, whereas under Linux the line ending is n, which needs no conversion to n. When writing a text file, Windows converts n to rn, whereas Linux needs no conversion for its line endings.

Changing the second line to

FILE *fpo = fopen(argv[2], "wb");

should fix your issues.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement