Thursday, 21 September 2017

C++ program to add user defined contents to file and to read the file later

/*
 C++ program to add user defined contents to file and to read the file later
*/

#include "iostream"
#include "fstream" // required 
using namespace std;

int main(){
 /* Block to write user-defined contents to file */
 int count, age;
 string name;
 ofstream outFile;
 outFile.open("MyFile", ios::out); // writing ios::out is optional as object used is outFile
 if(outFile.is_open()){
  cout<<"\nSuccess .."<<endl;
  cout<<"\nHow many entries do you wish to add to file: ";
  cin>>count;
  for(int i=0; i<count; i++){
   cout<<"\nEnter name: ";
   cin>>name;
   cout<<"\nEnter age: ";
   cin>>age;
   
   outFile<<name<<"\t"<<age<<endl;  // adding contents to file
  }
 
  outFile.close();  // close the file
 }else{
  cout<<"\nFile creation and opening failed .. "<<endl;
 }

 /* Block to read from file */
 ifstream inFile;
 string line;     // to catch each statement of file

 inFile.open("MyFile", ios::in);  // in mode is optional for inFile object
 if(inFile.is_open()){
  cout<<"\nReading contents of file ..\n\n";
  while(getline(inFile, line)){
   cout<<line<<endl; // printing contents of file on console
  }
 
 }else{
  cout<<"\nFile not found ..";
 }
 return 0;
}

/*
 OUTPUT

[pavan@localhost Unit-5]$ g++ FileOp2.cpp
[pavan@localhost Unit-5]$ ./a.out 

Success ..

How many entries do you wish to add to file: 3

Enter name: Pavan

Enter age: 32

Enter name: Khushbu

Enter age: 28

Enter name: Nityant

Enter age: 2

Reading contents of file ..

Pavan 32
Khushbu 28
Nityant 2
[pavan@localhost Unit-5]$ 


*/

No comments: