【问题标题】:Binary output in WindowsWindows 中的二进制输出
【发布时间】:2011-07-05 17:16:29
【问题描述】:

我编写了一个程序,它读取一个二进制文件,对其内容进行一些处理并将结果写入另一个文件。在 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);
}

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

【问题讨论】:

    标签: c windows file-io stdio


    【解决方案1】:

    您应该使用b 标志来打开:

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

    我了解,由于某些 (brain-damage) 主观决定,如果文件未以“二进制模式”打开,则 win32 在输入流上达到 0x1A 时会触发EOF

    编辑

    我从未调查过它,但现在有人告诉我 0x1A 在 DOS 中用作软 EOF。

    【讨论】:

    • 这可能更多的是脑损伤而不是主观的 - eof 字符的原因是由于 Windows 与 CP/M 的史前连接,它只在扇区(或集群?)粒度上跟踪文件的大小.
    • @Michael Burr 如果您有更多相关信息,我会很高兴的。
    • 没有更多信息 - CP/M 只知道文本文件在磁盘上占用了多少扇区;为了知道它何时应该停止从最后一个扇区读取数据,使用了哨兵 EOF 值,他们选择了ctrl-Z 作为那个哨兵。由于 MS-DOS 提供了与 CP/M 的某种程度的兼容性,因此它支持相同的方案。由于 Windows 带来了很多 DOS 包袱,我们就到这里了。
    • 关于答案的说明:目标文件还需要"b" 标志,否则二进制写入将在 Windows 上损坏。
    【解决方案2】:

    好吧,您不是以二进制模式打开文件(使用“wb”和“rb”)。这在 Linux 上无关紧要,但在 Windows 上确实如此,它会在以文本模式读取/写入文件时转换某些字节。例如:

    \r\n <--> \n 
    
    \x1a  (Ctrl-Z) is treated as an EOF indicator
    

    【讨论】:

      【解决方案3】:

      您需要在 fopen 中使用“rb”和“wb”。

      【讨论】:

        猜你喜欢
        • 2017-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多