C++ Program to Append a String in an Existing File

Here, we will build a C++ program to append a string in an existing file using 2 approaches i.e.

  1. Using ofstream
  2. Using fstream

C++ programming language offers a library called fstream consisting of different kinds of classes to handle the files while working on them. The classes present in fstream are ofstream, ifstream and fstream. 

The file we are considering the below examples consists of the text “Beginner for Beginner“. 

1. Using “ofstream“

In the below code we appended a string to the “Beginner for Beginner.txt” file and printed the data in the file after appending the text.  The created ofstream “ofstream of” specifies the file to be opened in write mode and ios::app in the open method specifies the append mode.

C++




// C++ program to demonstrate appending of
//  a string using ofstream
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
    ofstream of;
    fstream f;
   
    // opening file using ofstream
    of.open("Beginner for Beginner.txt", ios::app);
    if (!of)
        cout << "No such file found";
    else {
        of << " String";
        cout << "Data appended successfully\n";
        of.close();
        string word;
       
        // opening file using fstream
        f.open("Beginner for Beginner.txt");
        while (f >> word) {
            cout << word << " ";
        }
        f.close();
    }
    return 0;
}


Output:

Data appended successfully
Beginner for Beginner String

2. Using “fstream“

In the below code we appended a string to the “Beginner for Beginner.txt” file and printed the data in the file after appending the text. The created fstream “fstream f” specifies the file to be opened in reading & writing mode and ios::app in the open method specifies the append mode.

C++




// C++ program to demonstrate appending of
// a string using fstream
#include <fstream>
#include <string>
using namespace std;
int main()
{
    fstream f;
    f.open("Beginner for Beginner.txt", ios::app);
    if (!f)
        cout << "No such file found";
    else {
        f << " String_fstream";
        cout << "Data appended successfully\n";
        f.close();
        string word;
        f.open("Beginner for Beginner.txt");
        while (f >> word) {
            cout << word << " ";
        }
        f.close();
    }
    return 0;
}


Output:

Data appended successfully
Beginner for Beginner String_fstream


Contact Us