Binary Read/Write
2002-02-02 15:05:54
Category: c:files
Description: Example of writing a struct to a binary file and then reading it back in.
Author: detour
Viewed: 28223
Rating: (129 votes)


/* binaryrw.c written by detour@metalshell.com
 *
 * Example of writing a struct to a binary file and then
 * reading it back in.
 *
 * http://www.metalshell.com/
 *
 */
 
#include <stdio.h>
 
struct zigzag {
  int a;
  char b[20];
};
 
int writeBinary(const struct zigzag);
int readBinary(struct zigzag *);
 
int main() {
  struct zigzag myZig, inZig;
  struct zigzag *ptr;
 
  /* the memory address we will send to readbinary */
  ptr = &inZig;
 
  /* assign some dummy values */
  myZig.a = 24;
  strcpy(myZig.b, "Blubber");
 
  /* Write the struct myZig and then read it back in */
  if(writeBinary(myZig))
    exit(1);
  if(readBinary(ptr))
    exit(1);
 
  /* proof that it was successful */
  printf("inZig.a: %d\n", inZig.a);
  printf("inZig.b: %s\n", inZig.b);
}
 
 
int writeBinary(const struct zigzag j) {
  FILE *outFile;
 
  /* open the file we are writing to */
  if(!(outFile = fopen("binout", "w")))
     return 1;
 
  /* use fwrite to write binary data to the file */
  fwrite(&j,sizeof(struct zigzag),1,outFile);
 
  fclose(outFile);
 
  return 0;
}
 
int readBinary(struct zigzag *b) {
  FILE *inFile;
 
  if(!(inFile = fopen("binout", "r")))
    return 1;
 
  fread((struct zigzag *)b,sizeof(struct zigzag),1,inFile);
 
  fclose(inFile);
 
  return 0;
}