如何在c中读取二进制文件? (视频、图像或文字)
我正在尝试将文件从指定的库复制到当前目录。我可以完美地复制文本文件。任何其他文件都会损坏。程序提前检测到 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;
}
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.
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您使用的是 Windows 机器吗?尝试将“b”添加到调用
fopen
的模式字符串中。来自 man fopen(3):
Are you on a Windows machine? Try adding "b" to the mode strings in the calls to
fopen
.From man fopen(3):
您需要为
fopen
指定"b"
选项:如果没有它,文件将以文本 (
"t"
) 模式打开,并且这会导致行尾字符的翻译。You need to specify the
"b"
option tofopen
:Without it, the file is opened in text (
"t"
) mode, and this results in translation of end-of-line characters.您需要以二进制格式而不是文本格式打开文件。在调用
fopen
时,使用"rb"
和"wb"
而不是"r"
和“w”
分别。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.