Binary output in Windows

亡梦爱人 提交于 2020-01-04 09:37:11

问题


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.



来源:https://stackoverflow.com/questions/6586382/binary-output-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!