C语言 如何在c中读取二进制文件?(视频、图像或文本)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2307057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:34:16  来源:igfitidea点击:

How to read a binary file in c? (video, images, or text)

cfread

提问by Collin Price

I am trying to copy a file from a specified library to the current directory. I can copy text files perfectly. Any other files become corrupt. The program detects a feof before it should.

我正在尝试将文件从指定的库复制到当前目录。我可以完美地复制文本文件。任何其他文件都会损坏。该程序在它应该之前检测到feof。

#include <stdio.h>

int BUFFER_SIZE = 1024;
FILE *source;
FILE *destination;
int n;
int count = 0;
int written = 0;

int main() {
    unsigned char buffer[BUFFER_SIZE];

    source = fopen("./library/rfc1350.txt", "r");

    if (source) {
        destination = fopen("rfc1350.txt", "w");

        while (!feof(source)) {
            n = fread(buffer, 1, BUFFER_SIZE, source);
            count += n;
            printf("n = %d\n", n);
            fwrite(buffer, 1, n, destination);
        }
        printf("%d bytes read from library.\n", count);
    } else {
        printf("fail\n");
    }

    fclose(source);
    fclose(destination);

    return 0;
}

回答by Hans W

Are you on a Windows machine? Try adding "b" to the mode strings in the calls to fopen.

你在 Windows 机器上吗?尝试将“b”添加到调用中的模式字符串fopen

From man fopen(3):

来自 man fopen(3):

The mode string can also include the letter 'b' either as a last character or as a character between the characters in any of the two-character strings described above. This is strictly for compatibility with C89 and has no effect; the 'b' is ignored on all POSIX conforming systems, including Linux. (Other systems may treat text files and binary files differently, and adding the 'b' may be a good idea if you do I/O to a binary file and expect that your program may be ported to non-Unix environments.)
模式字符串还可以包括字母“b”作为最后一个字符或作为上述任何两个字符串中的字符之间的字符。这严格是为了兼容 C89,没有任何影响;'b' 在所有符合 POSIX 的系统上都被忽略,包括 Linux。(其他系统可能会以不同的方式对待文本文件和二进制文件,如果您对二进制文件进行 I/O 操作并希望您的程序可以移植到非 Unix 环境,那么添加 'b' 可能是个好主意。)

回答by Thomas

You need to specify the "b"option to fopen:

您需要将"b"选项指定为fopen

source = fopen("./library/rfc1350.txt", "rb");
...
destination = fopen("rfc1350.txt", "wb");

Without it, the file is opened in text ("t") mode, and this results in translation of end-of-line characters.

如果没有它,文件将以文本 ( "t") 模式打开,这将导致行尾字符的翻译。

回答by user200783

You need to open the files in binary format rather than text format. In your calls to fopen, use "rb"and "wb"rather than "r"and "w"respectively.

您需要以二进制格式而不是文本格式打开文件。在您对 的调用中fopen,分别使用"rb"and"wb"而不是"r"and "w"