Windows中的二进制输出

mig*_*rso 2 c windows file-io stdio

我写了一个程序,它读取一个二进制文件,对其内容进行一些处理,并将结果写入另一个文件.在Linux中它可以很好地工作,但在Windows中它不起作用; 输出文件总是1KB ...

这是该程序的简化版本:

#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);
}
Run Code Online (Sandbox Code Playgroud)

我很乐意为您提供有关该问题的更多详细信息,但我没有太多在Windows中编写C语言的经验,我真的不知道问题出在哪里.

cni*_*tar 7

您应该使用b标志fopen:

fopen(source, "rb")
fopen(destination, "wb");
Run Code Online (Sandbox Code Playgroud)

据我所知,由于某些(脑损伤)主观决定,在输入流上的win32到达0x1A时触发一个EOF文件未在"二进制模式"下打开.

编辑

从来没有调查过,但现在有人告诉我,0x1A在DOS中用作软EOF.

  • @Michael Burr如果你有更多的信息,我真的很喜欢它. (2认同)