0

我必须读取一个二进制 (.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 技术。

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

4

2 回答 2

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);
}
于 2013-04-03T16:33:40.010 回答
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];
    }
}
于 2013-04-03T16:18:50.247 回答