Friday, July 20, 2012

Binary File I/O in ANSI C

The ANSI C library stdio.h provides functions for reading and writing binary files. If you are not familiar with stream operations in ANSI C you should read this first.

size_t fread(void *array, size_t size, size_t count, FILE *stream)
Description:
The function reads from the stream into the array count objects of the size size.
Returns:
The function returns the number of read objects. This number may be smaller than the requested number of objects.

size_t fwrite(const void *array, size_t size, size_t count, FILE *stream)
Description:
The function writes to the stream count objects of the array having the size size.
Returns:
The function returns the number of written objects. If the return value is smaller than count, then an error happened.

Example
#include<stdio.h>

#define MAX_NAME_SIZE    80
#define MAX_EMAIL_SIZE   60
#define MAX_PERSONS      10

typedef struct
{
   char name[MAX_NAME_SIZE];
   int age;
   double salary;
   char email[MAX_EMAIL_SIZE];
}Person;

int main(void)
{
   Person persons[MAX_PERSONS] =
   {
       {"Clark Kent", 30, 3250.5, "superman@krypton.com"},
       {"Peter Griffin", 40, 1250.0, "birdmaster@familyguy.com"},
       {"Stewie Griffin", 3, 50000.0, "world_domination@familyguy.com"},
       {"Eric Cartman", 12, 50000.0, "autoritah@southpark.com"},
       {"Zapp Brannigan", 30, 200.5, "stargeneral@futurama.com"},
   };
   Person pCopy[MAX_PERSONS];
   FILE* f = NULL;
   int i;
   /*Opens the stream in <writing binary> mode*/
   f = fopen("persons.bin","wb");
   if(f!=NULL)
   {
      /*Writes 5 Person objects into the binary file*/
      fwrite(&persons, sizeof(Person), 5, f);
      /*Closes the stream*/
      fclose(f);
      /*Reopens the stream in <read binary> mode*/
      f = fopen("persons.bin","rb");
      if(f!=NULL)
      {
         /*Reads 5 Person objects from the binary file into another vector*/
         fread(&pCopy,sizeof(Person),5,f);
         /*Prints the results*/
         for(i = 0; i<5; i++)
         {
            printf("%s %d %f %s\n",pCopy[i].name,pCopy[i].age,
                                   pCopy[i].salary,pCopy[i].email);
         }
         /*Closes the stream*/
         fclose(f);
      }
   }
   return 0;
}

2 comments:

  1. Does this work on all types of files?
    And what if you are reading a large binary file, that is, the size is larger than the third argument of the read/write function?

    ReplyDelete
    Replies
    1. To my knowledge, the read/write functions work on all binary files.

      Regarding the size, the function will only read the first n entries (where n is your third argument).

      Delete

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger