Sunday, 6 May 2012

Simple File Handling in C


#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>


struct goods {
   char a[20];    
   float price;
   int quantity;   
   int reorder;    
};


void myexit( int );
void profile( void );
void prntrec( struct goods );
int getrec( struct goods * );


FILE *fopen(), *ip;  


void myexit( int exitcode )
{
   if( ip != NULL )
      fclose( ip );
   exit( exitcode );
}


void prntrec( struct goods database )
{
   printf("\nProduct a\t%s\n", database.a );
   printf("Product price\t%.2f\n", database.price );
   printf("Product quantity\t%d\n", database.quantity );
   printf("Product reorder level\t%d\n", database.reorder );
}


int getrec( struct goods *database )
{
   int loop = 0, ch;
   char buffer[40];


   ch = fgetc( ip );


   while( (ch == '\n') || (ch == ' ') && (ch != EOF) )
      ch = fgetc( ip );
   if( ch == EOF ) return 0;


   while( (ch != '\n') && (ch != EOF)) {
      buffer[loop++] = ch;
      ch = fgetc( ip );
   }
   buffer[loop] = 0;
   strcpy( database->a, buffer );
   if( ch == EOF ) return 0;


   while( (ch == '\n') || (ch == ' ') && (ch != EOF) )
      ch = fgetc( ip );
   if( ch == EOF ) return 0;


   loop = 0;
   while( (ch != '\n') && (ch != EOF)) {
      buffer[loop++] = ch;
      ch = fgetc( ip );
   }
   buffer[loop] = 0;
   database->price = atof( buffer );
   if( ch == EOF ) return 0;


   while( (ch == '\n') || (ch == ' ') && (ch != EOF) )
      ch = fgetc( ip );
   if( ch == EOF ) return 0;


   loop = 0;
   while( (ch != '\n') && (ch != EOF)) {
      buffer[loop++] = ch;
      ch = fgetc( ip );
   }
   buffer[loop] = 0;
   database->quantity = atoi( buffer );
   if( ch == EOF ) return 0;


   while( (ch == '\n') || (ch == ' ') && (ch != EOF) )
      ch = fgetc( ip );
   if( ch == EOF ) return 0;


   loop = 0;
   while( (ch != '\n') && (ch != EOF)) {
      buffer[loop++] = ch;
      ch = fgetc( ip );
   }
   buffer[loop] = 0;
   database->reorder = atoi( buffer );
   if( ch == EOF ) return 0;


   return 1;  
}


void profile( void )
{
   struct goods database;  


   while( ! feof( ip )) {
      if( getrec( &database ) == 1 ) {
         if( database.quantity <= database.reorder )
            prntrec( database );
      }
      else myexit( 1 );  
   }
}


main()
{
   char filename[40];    
   printf("\n");
   printf("Enter database file ");
   scanf(" %s", filename );
   ip = fopen( filename, "rt" );
   if( ip == NULL ) {
      printf("Unable to open datafile %s\n", filename );
      myexit( 1 );
   }
   profile();
   myexit( 0 );
   getch();
   return 0;
}

No comments:

Post a Comment