How to append text to a text file in C++?


This is a C++ program to append text to a text file.

Algorithm

Begin
   Open that file a1.txt as output file stream class object to perform
   output operation in append mode using fout file reference.
   If the file exists then
      Appending text to that file.
   Close fout.
   Open the file “a1.txt” for reading the content of the file.
   Extracting the text from file and printing the text.
End.

Example Code

 Live Demo

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main() {
   fstream f;
   ofstream fout;
   ifstream fin;
      fin.open("a1.txt");
      fout.open ("a1.txt",ios::app);
   if(fin.is_open())
      fout<<" tutorials point";
      cout<<"\n Data has been appended to file"<<endl;
      fin.close();
      fout.close();
      string word;
      f.open("a1.txt");
      while (f >> word) {
         cout << word << " ";
      }
      return 0;
}

Output

Data has been appended to file

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements