In this tutorial, we are working with the files in the C++ or you have known to work with files as the file handling. 

File handling in any language requires Three main step to follow

  1. Open the file in Read/Write mode.
  2. Do various operation that you want to do.
  3. Close the file.

So In CPP, you can also use the traditional approach of C using FILE pointer and etc.

We are using fstream (file stream).

Without wasting much time lets start working.

Create a New CPP file of whatever name you want mine is files.cpp.

create the boiler plate code of c++.

#include <iostream>  
  
using namespace std;  
  
int main() {  
  
 return 0;  
}  

To work with file add two more header
first is #include , and second is #include

#include <fstream>  
#include <string>

Now, let’s start working with the writing into the files, to write into the file we need to open the file into the Write mode. 
Which can be done by the ofstream class of cpp from the fstream header.

        string filename = "demo.txt";  
 ofstream output;  
 //c_str() converts the string to the c char array.  
 output.open(filename.c_str());  

now we have the file ready to write but before writing into the file just check that file is opened successfully or not.

if (output.is_open()) {  
 output << "this is the Code In Cafe" << endl;  
 output << "this is the second line from the code in cafe";  
 output.close();  
}

output.close() closes the file.

Now open the same file into the Reading mode.
To open a file into the reading mode using ifstream.

string line;  
ifstream myfile;  
myfile.open(filename.c_str());  
if (myfile.is_open()) {  
 while (getline(myfile, line)) {  
  cout << line << endl;  
 }  
 myfile.close();  
}

Now you have written full program let’s run this program using g++.

output

full program code is given below

#include <iostream>  
#include <fstream>  
#include <string>  
  
using namespace std;  
  
int main() {  
 // saving into the files  
 string filename = "demo.txt";  
 ofstream output;  
 //c_str() converts the string to the c char array.  
 output.open(filename.c_str());  
 // this ensure that file is opened successfully  
 if (output.is_open()) {  
  output << "this is the Code In Cafe" << endl;  
  output << "this is the second line from the code in cafe";  
  output.close();  
 }  
 string line;  
 ifstream myfile;  
 myfile.open(filename.c_str());  
 if (myfile.is_open()) {  
  while (getline(myfile, line)) {  
   cout << line << endl;  
  }  
  myfile.close();  
 }  
 return 0;  
}  

Thanks for being here.
If you have liked this article, then consider sharing this article among your friends.

If you have any problem or suggestion, use comment boxes.