Answer to Question #180344 in C++ for Deepanshi singh

Question #180344

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


1
Expert's answer
2021-04-12T17:55:36-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS