Thursday, 21 September 2017

C++ program to create, write and read from data file

/*
 C++ program to create, write and read from data file
*/

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

int main(){
 /* Block to write to file */
 ofstream outFile;
 outFile.open("MyFile", ios::out); // writing ios::out is optional as object used is outFile
 if(outFile.is_open()){
  cout<<"\nSuccess .."<<endl;
  outFile<<"First Line added to file. \n"; // operator << have been overloaded for putting contents into file
  outFile<<"Second line even added. \n"; 
 
  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++ FileOp1.cpp
[pavan@localhost Unit-5]$ ./a.out 

Success ..

Reading contents of file ..

First Line added to file. 
Second line even added. 
[pavan@localhost Unit-5]$ 

*/

No comments: