Reading a Stream of Fields (Cont.)


The program below shows a way to implement the previous interface by using extraction and insertion operator overloading.

 ~wenchen/public_html/cgi-bin/351/week5/PurchaseBooks.cpp 
#include  <fstream>
#include  <iostream>
#include  <cstring>
  using namespace  std;
class Purchase {
  public:
    char  SSN[10];
    char  ISBN[13];
    char  quantity[6];
};
istream& operator>> ( istream& inFile, Purchase& p ) {

  inFile.get   ( p.SSN, 10 );
  if ( strlen( p.SSN ) == 0 )   return( inFile );
  inFile.ignore( 1, '|' );
  inFile.get   ( p.ISBN, 13);
  *(strrchr( p.ISBN, ' ' ) - 1 ) = '\0';
  inFile.ignore( 1, '|' );
  inFile.get   ( p.quantity, 6 );
  inFile.ignore( 1, '|' );
  inFile.ignore( 1, '\n' );
  return( inFile );
}
ostream&  operator<< ( ostream& outFile, Purchase& p ) {
  char  ISBN[13], quantity[6];
  char  spaces[13] = "            ";

  outFile.write( p.SSN, 9 );
  outFile << '|';
  strcpy ( ISBN, spaces );
  strncpy( ISBN, p.ISBN, strlen( p.ISBN ) );
  outFile.write( ISBN, 12 );
  outFile << '|';
  strcpy ( quantity, spaces );
  strncpy( quantity, p.quantity, strlen( p.quantity ) );
  outFile.write( quantity, 5 );
  outFile << '|' << endl;
  return( outFile );
}
int  main( ) {
  ifstream  file1;
  fstream   file2;
  char      SSN[10], ISBN[13], quantity[6];
  Purchase  p;
  long      pos;

  strcpy( SSN,      argv[1] );
  strcpy( ISBN,     argv[2] );
  strcpy( quantity, argv[3] ); 
  file1.open( "buys.txt", fstream::in );
  for ( ; ; ) {
    pos = file1.tellg( );
    file1 >> p;
    if ( ( strlen( p.SSN ) == 0 ) ||
         ( ( strcmp( p.SSN,  SSN  ) == 0 ) &&
           ( strcmp( p.ISBN, ISBN ) == 0 ) ) ) {
      break;
    }
  }
  file1.close( );

  file2.open ( "buys.txt", fstream::in | fstream::out );
  file2.seekp( pos );
  strcpy( p.SSN, SSN );
  strcpy( p.ISBN, ISBN );
  strcpy( p.quantity, quantity );
  file2 << p;
  file2.close( );
}