Binary output in Windows

2019-07-18 07:47发布

问题:

I wrote a program that reads a binary file, does some process with its contents and writes the results to a different file. In Linux it works perfectly, but in Windows it does not work; the output files are always 1KB...

This is a simplified version of the program:

#include <stdio.h>

void copyFile(char* source, char* dest);

int main (int argc, char* argv[])
{
    if (argc != 3)
        printf ("usage: %s <source> <destination>", argv[0]);
    else
    {
        copyFile(argv[1], argv[2]);
    }
}


void encryptFile(char* source, char* destination)
{
    FILE *sourceFile;
    FILE *destinationFile;

    int fileSize;

    sourceFile = fopen(source, "r");
    destinationFile = fopen(destination, "w");

    if (sourceFile == 0)
    {
        printf ("Could not open source file\n");
        return;
    }

    if (destinationFile == 0)
    {
        printf ("Could not open destination file\n");
        return;
    }

    // Get file size
    fseek(sourceFile, 0, SEEK_END); // Seek to the end of the file
    if (ftell(sourceFile) < 4) 
        return; // Return if the file is less than 4 bytes
    fseek(sourceFile, 0, SEEK_SET); // Seek back to the beginning

    fseek(sourceFile, 0, SEEK_SET); // Seek back to the beginning

    int currentChar;

    while ((currentChar = fgetc(sourceFile)) != EOF)
    {
            fputc(currentChar, destinationFile);
    }

    fclose(sourceFile);
    fclose(destinationFile);
}

I would love to give you more details of the problem, but I don't have much experience programming C in Windows and I really don't know where may be the problem.

回答1:

You should use the b flag to fopen:

fopen(source, "rb")
fopen(destination, "wb");

I understand that due to some (brain-damage) subjective decisions, on win32 reaching 0x1A on the input stream triggers an EOF if the file is not opened in "binary mode".

EDIT

In never looked into it but somebody is telling me now that 0x1A was used in DOS as a soft EOF.



回答2:

Well, you're not opening the files in binary mode (use "wb" and "rb"). This doesn't matter on Linux, but it does on Windows, which will transform certain bytes when reading/writing a file in text mode. For example:

\r\n <--> \n 

\x1a  (Ctrl-Z) is treated as an EOF indicator


回答3:

You need to use "rb" and "wb" with fopen.