C++ program to Add record in FILE if new, otherwise Update the existing record in FILE

//program to read record of a book from user
//add this record in an existing file if the record does not exist in file
//otherwise update the existing record
//Use ISBN (i.e. one of data members of the class) to identify a book uniquely

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
class Book
{
  int ISBN;
  char name[20];
  public:
    void addBook()
    {
      cout<<endl<<"Enter ISBN: ";
      cin>>ISBN;
      cout<<endl<<"Enter book name: ";
      cin>>name;
    }
    void displayBook()
    {
      cout<<endl<<"ISBN: "<<ISBN;
      cout<<endl<<"Book name: "<<name;
    }
    char getISBN()
    {
      return ISBN;
    }
};
int main()
{
  Book b;
  int isFound,searchISBN;
 
fstream file("Book search by ISBN.txt",ios::in | ios::out | ios::binary | ios::ate | ios::app);
  cout<<endl<<"Search ISBN: ";
  cin>>searchISBN;
  file.clear();
  isFound=0;
  file.read((char*)&b,sizeof(b));
  while(file.eof()==0)
  {
    if(b.getISBN()==searchISBN)
    {
      cout<<endl<<"ISBN already exists...";
      isFound=1;
      break;
    }
    file.read((char*)&b,sizeof(b));
  }
  if(isFound==0)
  {
    cout<<endl<<"Entering new book record: ";
    b.addBook();
    file.seekp(0,ios::end);
    file.write((char*)&b,sizeof(b));
    file.close();
  }
  return 0;
}

No comments:

Post a Comment