Write a program in c++ to open & read the contents of the text1.txt using the file stream class, close the file and again open to update the contents of the given file text 1.txt
Text1.txt: I m enjoying learing oops concepts
After update
Text 1.txt: I m enjoying learing oops concepts now learnt c++; java is my next target
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fs;
string content;
fs.open("Text1.txt", fstream::in);
cout << "File contents:" << endl;
if(fs.is_open())
{
while(!fs.eof())
{
content = "";
fs >> content;
cout << content << endl;
}
}
else
{
cout << "File haven't been opened:(" << endl;
exit(0);
}
fs.close();
fs.open("Text1.txt",fstream::out | fstream::app);
if(fs.is_open())
{
content = "Now learnt C++; Java is my next target";
fs << content;
cout << "File contents:" << endl;
fs.seekg(0);
while(!fs.eof())
{
content = "";
fs >> content;
cout << content << endl;
}
}
else
cout << "File haven't been opened:(" << endl;
fs.close();
return 0;
}
Comments
Leave a comment