Taher
Taher

Reputation: 12040

Read the first integer in a binary file

Having a binary file that holds:

# hexdump file.pak 
0000000 09 00 00 00 
0000004

trying to read it with fread results in :

int main(void){
  char *filename = "file";
  FILE *fh = header_open(filename);
  header_init(fh);
  header_read_num_files(fh);
  header_close(fh);
}

FILE *header_open(char *pkg_file){
  FILE *fh;
  // open file with binary/read mode                                                                                                                                               
  if ( (fh = fopen(pkg_file, "ab")) == NULL){
    perror("fopen");
    return NULL; // todo: ...                                                                                                                                                      
  }

  return fh;
}

int header_read_num_files(FILE *fh){
  fseek(fh, 0L, SEEK_SET);
  char c;
  fread(&c, sizeof(char), 1, fh);
  fprintf(stderr,"buff received: %d\n", c);
}

/* write first 0 for number of files */
void header_init(FILE *fh){
  unsigned int x= 9;
  fseek(fh, 0, SEEK_SET);
  fwrite( (const void*)&x, sizeof(int), 1, fh);
}


output: buff received: 112

My system uses the small-endianness conversion. but still the other bytes are set to zero, I cannot really see why I'm getting this output.

An explanation is much appreciated.

Upvotes: 0

Views: 2068

Answers (1)

mikithskegg
mikithskegg

Reputation: 816

You open the file with "ab" option. Bur this option does not allow to read from file, only writing to its end is alloowed. Try to open this way

fh = fopen(pkg_file, "w+b")

Upvotes: 1

Related Questions