C 如何读取bin文件的内容,直到没有剩余数据
我必须读取二进制(.bin)文件。此文件包含RGBA数据的视频数据。每个组件由4096个字节组成,类型为无符号字符。因此,我打开文件并读取文件,如下代码段所示:C 如何读取bin文件的内容,直到没有剩余数据,c,file,fread,C,File,Fread,我必须读取二进制(.bin)文件。此文件包含RGBA数据的视频数据。每个组件由4096个字节组成,类型为无符号字符。因此,我打开文件并读取文件,如下代码段所示: FILE *fp=fopen(path,"rb"); //Allocating memory to copy RGBA colour components unsigned char *r=(unsigned char*)malloc(sizeof(unsigned char)*4096); unsigned char *g=(unsi
FILE *fp=fopen(path,"rb");
//Allocating memory to copy RGBA colour components
unsigned char *r=(unsigned char*)malloc(sizeof(unsigned char)*4096);
unsigned char *g=(unsigned char*)malloc(sizeof(unsigned char)*4096);
unsigned char *b=(unsigned char*)malloc(sizeof(unsigned char)*4096);
unsigned char *b=(unsigned char*)malloc(sizeof(unsigned char)*4096);
//copying file contents
fread(r,sizeof(unsigned char),4096,fp);
fread(g,sizeof(unsigned char),4096,fp);
fread(b,sizeof(unsigned char),4096,fp);
fread(a,sizeof(unsigned char),4096,fp);
在r、g、b、a中复制数据后,会将其发送至适当的显示功能。
上面的代码可以很好地复制一组RGBA数据。但是,我应该继续复制并发送数据以供显示
我搜索过,只能找到显示文件内容的示例,但它仅适用于文本文件,即EOF技术
因此,我恳请用户为将上述代码片段插入循环(循环条件)提供合适的建议。我认为EOF技术在这里就可以了,比如:
while (!feof(fp))
fread(buffer, sizeof(unsigned char), N, fp);
您的文件中是否有(R、G、B、A)值
int next\u r=0;
int next_g=0;
int next_b=0;
int next_a=0;
#定义n4096
而(!feof(fp))
{
int howmany=fread(缓冲区,sizeof(无符号字符),N,fp);
for(int i=0;ifread有一个返回值。如果出现错误,您需要检查它
fread()和fwrite()返回成功读取或写入的项目数(即,不是字符数)。
如果发生错误,或到达文件末尾,则返回值为短项计数(或零)
因此,您希望尝试执行fread,但一定要查找错误
while (!feof(fp) {
int res = fread(r,sizeof(unsigned char),4096,fp);
if (res != 4096) {
int file_error = ferror(fp)
if (0 != file_error) {
clearerr(fp)
//alert/log/do something with file_error?
break;
}
}
//putting the above into a function that takes a fp
// and a pointer to r,g,b, or a would clean this up.
// you'll want to wrap each read
fread(g,sizeof(unsigned char),4096,fp);
fread(b,sizeof(unsigned char),4096,fp);
fread(a,sizeof(unsigned char),4096,fp);
}
我们需要更多详细信息。您是否需要重新打开同一个文件并显示其更新内容,或者您是否需要按顺序打开并显示一组文件(即:生成视频)?如果是,这些文件的命名约定/模式是什么?或者是文件包含n
组RGBA数据,因此文件的大小是n*(4*4096)
?没有一个单独的文件只打开一次,并且一旦文件打开,我们需要在一个循环中继续读取(fread)rgba数据和显示。感谢您的回复。我所需要的只是while(!feof(fp))条件。其余我可以轻松继续。再次感谢。
while (!feof(fp) {
int res = fread(r,sizeof(unsigned char),4096,fp);
if (res != 4096) {
int file_error = ferror(fp)
if (0 != file_error) {
clearerr(fp)
//alert/log/do something with file_error?
break;
}
}
//putting the above into a function that takes a fp
// and a pointer to r,g,b, or a would clean this up.
// you'll want to wrap each read
fread(g,sizeof(unsigned char),4096,fp);
fread(b,sizeof(unsigned char),4096,fp);
fread(a,sizeof(unsigned char),4096,fp);
}