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;"MyFile", ios::out); // writing ios::out is optional as object used is outFile
  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
  cout<<"\nFile creation and opening failed .. "<<endl;

 /* Block to read from file */
 ifstream inFile;
 string line;     // to catch each statement of file"MyFile", ios::in);  // in mode is optional for inFile object
  cout<<"\nReading contents of file ..\n\n";
  while(getline(inFile, line)){
   cout<<line<<endl; // printing contents of file on console
  cout<<"\nFile not found ..";
 return 0;

[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: