File Handling


    
    

There are three classes included in C++ to work with files:

  • ofstream - creates and writes to files
  • ifstream - reads from files
  • fstream - a combination of ofstream and ifstream (can create, read, and write).


Table of Contents

  1. ofstream
  2. ifstream
  3. fstream

ofstream (Create and Write to a File)

To write to a file, first we need to include the library <fstream>, then we open the file with ofstream class or fstream class. Then we use the insertion operator (<<) to write and finally, we close the file.

Syntax: fprintf(pointer_name, "text we want to write");

Example:

#include <iostream> #include <fstream> using namespace std; int main() { // Create and open a text file ofstream MyFile("filename.txt"); // Write to the file MyFile << "Hello!"; // Close the file MyFile.close(); }

We can also append to a file using ofstream. But, we need to include the mode std::ios::app in the open() function.

Syntax: variable_name.open(file_name, std::ios::app);

Example:

#include <iostream> #include <fstream> using namespace std; int main() { // Declaring a variable ofstream myfile; // Open and append "Hello!" the file myfile.open("text.txt", ios::app) myfile << "Hello!" // Close the file myfile.close(); return 0; }

ifstream (Read a File)

To read a file, first we need to include the library <fstream>, then we open the file with ifstream class or fstream class. We need to prepare a text string variable to store the file content. Then, we use the getline() function and finally, we close the file.
Note: getline() function only read a single line of text, so if you want to read several line of text, use loops to loop through the getline() function.

Example:

#include <iostream> #include <fstream> using namespace std; int main() { //Create a variable string string mytext; // Read from the text file ifstream MyFile("filename.txt"); // Read the file using getline() function getline(MyFile, mytext); cout << mytext; // Close the file MyFile.close(); }

fstream

fstream can do both what ifstream and ofstream does. Example:

#include <iostream> #include <fstream> using namespace std; int main() { // Create and open a text file fstream MyFile("filename.txt"); // Write to the file MyFile << "Hello!"; // Close the file MyFile.close(); }
#include <iostream> #include <fstream> using namespace std; int main() { //Create a variable string string mytext; // Read from the text file fstream MyFile("filename.txt"); // Read the file using getline() function getline(MyFile, mytext); cout << mytext; // Close the file MyFile.close(); }