Write a program in C++ to open and read the contents of the Text1.txt using the file stream class.
Close the file and again open to update the contents of given file Text1.txt.
Text1.txt : I am enjoying learning OOPS concepts
After update
Text1.txt: I am enjoying learning OOPS concepts
Now learnt C++; Java is my next target.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
string line;
//open file READ
ifstream infile;
infile.open ("Text1.txt");
// read data from file to line[]
cout<<"Befor:"<<endl;
// while (!infile.eof()) // read to line until the end
getline(infile, line);
infile.close();
// display data
cout<<line<<endl;
//open file WRITE
ofstream outfile;
outfile.open ("Text1.txt");
outfile << "Now learnt C++; Java is my next target.\n";
outfile.close();
cout<<"After:"<<endl;
//open file READ
infile.open ("Text1.txt");
// while (!infile.eof()) // read to line until the end
getline(infile, line);
infile.close();
// display file
cout<<line<<endl;
return 0;
}
Comments
Leave a comment