Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 “Geeks for Geeks“. 

1. Using “ofstream

In the below code we appended a string to the “Geeks for Geeks.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("Geeks for Geeks.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("Geeks for Geeks.txt");
        while (f >> word) {
            cout << word << " ";
        }
        f.close();
    }
    return 0;
}


Output:

Data appended successfully
Geeks for Geeks String

2. Using “fstream

In the below code we appended a string to the “Geeks for Geeks.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("Geeks for Geeks.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("Geeks for Geeks.txt");
        while (f >> word) {
            cout << word << " ";
        }
        f.close();
    }
    return 0;
}


Output:

Data appended successfully
Geeks for Geeks String_fstream


Last Updated : 28 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads