0

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.

5
  • 2
    You need to check the return values of these functions to make sure they succeeded. Commented Feb 16, 2012 at 21:58
  • 2
    You are opening the file in "append" mode, not "read" mode. You have to pass "rb" as second argument to fopen! Commented Feb 16, 2012 at 22:17
  • @Gandaro, I've been trying to avoid reopening the file for efficiency, do you think this is relevant? what's the point of the `a' flag then? Commented Feb 16, 2012 at 22:25
  • 2
    It is used to append stuff to files?! Appending and reading are two completely different things… Commented Feb 16, 2012 at 22:30
  • yes, read and replace mainly. Commented Feb 16, 2012 at 22:34

1 Answer 1

1

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")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a bunch! though I used a+b instead since I don't my file truncated if it exists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.