Add a new line to text file in C++

In this article, we are going to see how we can add a new line to a text file using C++.

In the text file data is stored in the form of ASCII characters. In-text files,  EOL (End Of Line) character is a special character that terminates the line of text.

Append mode

To add a new line, we open the file in the append mode, where we can add the data at the end of the file.

ofstream foutput;
foutput.open ("abc.txt",ios::app);

foutput is the object of the ofstream class.

C++ program to add a new line to our text file

Now, its time to write the code to perform our task. So below is our C++ code:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
 ofstream foutput; 
 ifstream finput;

 finput.open ("apnd.txt");
 foutput.open ("apnd.txt",ios::app); 
 
 if(finput.is_open())
   foutput<<"\nWrite here whatever you want to store in the text file.\n"; 
  
 cout<<"\n Data has been appended to file";
 
 finput.close();
 foutput.close(); 
 
 return 0;
}

Create a text file by the name “apnd.txt”.
Enter some data in it.

Output:

Text file content:

This code is wriiten in C++.
This code is about adding new line in the text file.

After compiling,

Output on the screen:

Data has been appended to file

Updated text file content:

This code is wriiten in C++.
This code is about adding new line in the text file.
Write here whatever you want to store in the text file. 

Explanation:

Its time to explain our code so that you can understand what we exactly did.

In our code, we first open our text file in read mode and also in append mode. If the file is available and opened then we can input the data in the text file. After that, we close the text files.

I hope this tutorial is helpful to you.

Also Read: How to remove blank lines from a text file using C++?

2 responses to “Add a new line to text file in C++”

  1. ziauddin says:

    //Program to write data in a fine in a new line after the old/already existing data
    //Editor used: MS visual studio 2019
    //File name in the same directory where c++ project is created is poly
    //with .txt extension
    #include
    #include
    #include
    using namespace std;
    int main()
    {
    fstream file;
    file.open(“poly.txt”, ios::out | ios::app);
    if (!file) {
    cout << "File does not exist\n";
    }
    else
    {
    cout << "Writing\n";
    file << "\nResult: 4×4 + 6×3 + 56×2 + 33×1 + 3×0";
    }
    system("pause");
    return 0;
    }

    //When you run the program this will give the following output
    //Note :polynomial1 and polynomial2 were already written
    //I just wrote the result manually to show how to write data into a file in new line

    polynomial1: 2×3 + 56×2-1×1+3×0
    polynomial2: 4×4+4×3+34×1+x0
    Result: 4×4 + 6×3 + 56×2 + 33×1 + 3×0

Leave a Reply

Your email address will not be published. Required fields are marked *