I have a binary file format with header and body. The header fields and number of bytes for every of it is
- Magic: 1
- Header_size: 2
- Version: 1
- No_of_sections: 1
- Section_headers: No_of_sections * sizeof(section_header) Section Header: 17+4+4+4 Sect_name: 17; Sect_type: 4; Sect_offset: 4; Sect_size: 4
I need to verify some restrictions and print this
version=<version_number>
nr_sections=<no_of_sections>
section1: <NAME_1> <TYPE_1> <SIZE_1>
Restrictions:
- The value of the magic field must be 'Q'
- The values of the file version must be between 41 and 67, including that values.
- The number of sections must be between 3 and 10, including that values.
- The existing sections’ type must be only 44 68 35
I done the magic and version part, but i cant do the section part, it always prints some characters.
I know my code is really messy. Sorry for that :(
void parse(const char *path)
{
int fd;
unsigned char c[17];
char name[17];
int type;
off_t size;
fd = open(path, O_RDONLY);
size= lseek(fd,0,SEEK_END);
lseek(fd,0,SEEK_SET);
for(int i = 0 ; i <=size; i++)
{
lseek(fd,0,SEEK_CUR);
read(fd,&c,1);
if(i==0)
if(c[0]=='Q')
printf("SUCCESS\n");
if(i<5 && c[0]>=')' && c[0]<='C')
printf("version=%d \n", c[0]);
}
lseek(fd,5,SEEK_SET);
for(int j=1; j<10; j++)
{
read(fd, &name, 17);
name[17]='\0';
read(fd, &type, 4);
printf("section%d: %s %d\n", j + 1, name, type);
}
}
The second for shoud be
for(int j =1;j<=no_of_section;j++)
but i dont know the nr_of_section :( My output
SUCCESS
version=46
section2: fJ00pYisvmveDqS 44
section3: V 1515418709
section4: fRo 2054764888
section5: e6NpWyIifXZ -1392508919
section6: 738197570
section7: 1247047749
section8: J5ArY 1985282048
section9: 707OpGRoR8l9Yen# 381353984
section10: 2053662817
The output should be:
SUCCESS
version=46
nr_sections=7
section1: fJ00pYisvmveDqS 44 1016
section2: LLSWA0rSmUtSZfRo 44 890
section3: lX9yze6NpWyIifXZ 44 941
section4: de0cLp2V907jC9B 44 1178
section5: JrUrWEEpTJJ5ArY 68 724
section6: Uv707OpGRoR8l9Yen 35 1014
section7: BOWdKpZwrBaahhzz 44 972
Binary File exemple ( it includes only the header and 2 sections )
sizecome from?