如何读取C的二进制文件? (视频,图片或文字) [英] How to read a binary file in c? (video, images, or text)
本文介绍了如何读取C的二进制文件? (视频,图片或文字)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将文件从一个指定的库复制到当前目录。我可以完美复制的文本文件。任何其他文件损坏。该程序检测到的feof它应该之前。
的#include<&stdio.h中GT;INT BUFFER_SIZE = 1024;
FILE *源;
FILE *目的地;
INT N;
诠释计数= 0;
诠释书面= 0;诠释主(){
无符号字符缓冲区[BUFFER_SIZE]; 来源= FOPEN(./库/ rfc1350.txt,R); 如果(源){
目的地=的fopen(rfc1350.txt,W); 而(!的feof(源)){
N = FREAD(缓冲,1,BUFFER_SIZE,源);
数+ = N;
的printf(N =%d个\\ N,N);
FWRITE(缓冲,1,N,目的地);
}
的printf(%d字节从图书馆阅读\\ n,计数);
}其他{
的printf(失败\\ n);
} FCLOSE(源);
FCLOSE(目标); 返回0;
}
解决方案
您在Windows机器上?尝试添加B在通话模式字符串的fopen
。
从人的fopen(3):
<块引用>的模式串还可以包括字母b无论是作为一最后的字符或如上述任何两个字符的字符串的字符之间的字符。这是严格与C89的兼容性和没有影响;在B上的所有符合POSIX系统,包括Linux被忽略。 (其他系统可能将文本文件和二进制不同的文件,并添加B可能是一个好主意,如果你做的I / O
二进制文件,并期待您的程序可能被移植到非Unix
环境。)块引用>
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;
}
解决方案
Are you on a Windows machine? Try adding "b" to the mode strings in the calls to fopen
.
From 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.)
这篇关于如何读取C的二进制文件? (视频,图片或文字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文