Signup/Sign In

C++ Program To Read A Line By Line And Write Line By Line Using File

In this tutorial, we will be learning how to read and write line by line using files.

C++ Program To Read A Line By Line

Before moving to the implementation part, let's first understand the working of the algorithm:

Algorithm

1. Begin

2. Create an object newfile against the class fstream.

3. Call open() method to open a file “tpoint.txt” to perform write operation using object newfile.

4. If file is open then Input a string “Tutorials point" in the tpoint.txt file.

5. Close the file object newfile using close() method. Call open() method to open a file “tpoint.txt” to perform read operation using object newfile.

6. If file is open then Declare a string “tp”.

7. Read all data of file object newfile using getline() method and put it into the string tp. Print the data of string tp. Close the file object newfile using close() method. End.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
   fstream newfile;
   newfile.open("tpoint.txt",ios::out);  // open a file to perform write operation using file object
   if(newfile.is_open()) //checking whether the file is open
   {
      newfile<<"Studytonight \n";   //inserting text
      newfile.close();    //close the file object
   }
   newfile.open("tpoint.txt",ios::in); //open a file to perform read operation using file object
   if (newfile.is_open()){   //checking whether the file is open
      string tp;
      while(getline(newfile, tp)){ //read data from file object and put it into string.
         cout << tp << "\n"; //print the data of the string
      }
      newfile.close(); //close the file object.
   }
}


Studytonight

C++ Program To Write A Line By Line

To create a file, use either the ofstream or fstream class, and specify the name of the file. To write to the file, use the insertion operator ( << ).

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

int main (){
    ofstream myfile("CSC2134.txt");

    if(myfile.is_open())
    {
        string str;
        do{
            getline(cin, str);
            myfile<<str<< endl;
        }while(str!="");
        myfile.close();
    }
    else cerr<<"Unable to open file";

    return 0;
}

Conclusion

Here, in this tutorial, we have implemented the reading as well as writing the line by line using files.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.