如何在c中读取二进制文件?(视频,图像或文字)

Col*_*ice 7 c fread

我正在尝试将文件从指定的库复制到当前目录.我可以完美地复制文本文件.任何其他文件都会损坏.该程序在它应该之前检测到一个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;
}
Run Code Online (Sandbox Code Playgroud)

Han*_*s W 18

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

来自man fopen(3):

模式字符串还可以包括字母"b"作为最后一个字符或者作为上述任意两个字符串中的字符之间的字符.这完全是为了与C89兼容而没有效果; 所有符合POSIX标准的系统(包括Linux)都会忽略'b'.(其他系统可能会以不同方式处理文本文件和二进制文件,如果您对二进制文件执行I/O并且期望您的程序可能移植到非Unix环境,则添加"b"可能是一个好主意.)


Tho*_*mas 5

您需要指定以下"b"选项fopen:

source = fopen("./library/rfc1350.txt", "rb");
...
destination = fopen("rfc1350.txt", "wb");
Run Code Online (Sandbox Code Playgroud)

没有它,文件将以text("t")模式打开,这会导致行尾字符的转换.