Home
 
 
Search:  
C C++ Perl PHP Python HTML ShellScripts
 
 
  Coding Books
  Tutorials
  Search Code
  Browse Code
  Link to Us
  Site News
  Contact Metalshell
 
 
 
  Submit Code   Statistics
 



C: A Reference Manual (4th Edition)    (ISBN: 0133262243)


 

 List Price: $44.99
 Our Price: $31.49
 Used Price: $8.00

 Release Date: 05 October, 1994
 Manufacturer: Prentice Hall (Paperback)
 Sales Rank: 6,413

 Author: Samuel P. Harbison, Guy L., Jr. Steele









More Info

 Binary Read/Write 2002-02-02 15:05:54
 
Category: source:c:files
Description: Example of writing a struct to a binary file and then reading it back in.
Platform: unix/win
Author: detour
Viewed: 24835
Rating: 3.7/5 (125 votes)
If you have any questions about this piece of code or still need help, try posting your question on the forum.

 

Printable Version
binaryrw.c
/* 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;
}
Rate this code:
(Not Helpful)  (Very Helpful) 

 
 
   Developer.*  
   Blue Parrots  
   Technipal  
   Defy Magazine  
   Code Project  
   Prog. Heaven  


Got Money?