如何在没有数据的情况下读取bin文件的内容

时间:2013-04-03 16:15:01

标签: c file fread

我必须读取二进制(.bin)文件。该文件具有RGBA数据的视频数据。每个组件由4096个字节组成,类型为 unsigned char 。因此,我打开文件并读取文件,如下面的代码片段所示:

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技术。

因此,我请求用户提供合适的建议,将上面的代码片段插入循环(循环条件)。

2 个答案:

答案 0 :(得分:1)

fread有一个返回值。如果出现错误,您需要检查它。

  

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);
}

答案 1 :(得分:0)

我认为EOF技术在这里会做得很好,例如:

while (!feof(fp))
   fread(buffer, sizeof(unsigned char), N, fp);
您的文件中的

是否有(R,G,B,A)值?

int next_r = 0;
int next_g = 0;
int next_b = 0;
int next_a = 0;
#define N 4096

while (!feof(fp))
{
    int howmany = fread(buffer, sizeof(unsigned char), N, fp);

    for (int i=0; i<howmany; i+=4)
    {
        r[next_r++] = buffer[i];
        g[next_g++] = buffer[i+1];
        b[next_b++] = buffer[i+2];
        a[next_a++] = buffer[i+3];
    }
}