简体   繁体   中英

How to read contents of a bin file until there is no data left

I have to read a binary (.bin) file. This file has video data that is the RGBA data. Each component is compose of 4096 bytes and are of type unsigned char . Hence i open the file and read the file as shown below code snippet:

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

Once the data is copied in r,g,b,a they are sent for suitable function for displaying. The above code works fine for copying one set of RGBA data. However i should keep copying and keep sending the data for display.

I searched and could only find example of displaying contents of a file, however it is suitable only for text files ie the EOF technique.

Hence i kindly request the users to provide suitable suggestions for inserting the above code snippet into a loop(the loop condition).

fread has a return value. You want to check it in case of an error.

fread() and fwrite() return the number of items successfully read or written (ie, not the number of characters). If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).

So, you want to try to do an fread, but be sure to look for an error.

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

I think that an EOF technique would do just fine here, something like:

while (!feof(fp))
   fread(buffer, sizeof(unsigned char), N, fp);

in your file do you have (R,G,B,A) values?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM