miguelSantirso
miguelSantirso

Reputation: 1253

Binary output in Windows

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.

Upvotes: 2

Views: 224

Answers (3)

cnicutar
cnicutar

Reputation: 182674

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.

Upvotes: 7

Michael Burr
Michael Burr

Reputation: 340326

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

Upvotes: 3

001
001

Reputation: 13533

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

Upvotes: 1

Related Questions