🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to C++ Notes
Topic #101

C++ Files


C++ Files

The fstream library allows us to work with files.

To use the fstream library, include both the standard <iostream> AND the <fstream> header file:

Example

    #include <iostream>
#include <fstream>

There are three classes included in the fstream library, which are used to create, write or read files:

Class Description
ofstream Creates and writes to files
ifstream Reads from files
fstream A combination of ofstream and ifstream: creates, reads, and writes to files

Create and Write To a File

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 (<<).

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 << "Files can be tricky, but it is fun
enough!";

  //
Close the file
  MyFile.close();
}

Note: Why do we close the file? It is considered good practice, and it can clean up unnecessary memory space.


Read a File

To read from a file, use either the ifstream or fstream class, and the name of the file.

Note that we also use a while loop together with the getline() function (which belongs to the ifstream class) to read the file line by line, and to print the content of the file:

Example

// Create a
text string, which is used to output the text file
string myText;

// Read from the text file
ifstream MyReadFile("filename.txt");

// Use a while
loop together with the getline() function to read the file line by line
while (getline (MyReadFile,
myText)) {
  // Output the text from the file
  cout << myText;
}

// Close the file
MyReadFile.close();

Complete Reference

For a complete reference of classes and functions, go to our C++ fstream Reference.

Want to go beyond the notes?

Join CodingNow 2.0's C++ course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

C++ Files – FAQs

Quick answers about learning C++ Files in C++.

This free note from CodingNow 2.0 explains C++ Files in C++ — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every C++ topic on CodingNow 2.0, including C++ Files, is 100% free with no signup required.
With focused practice, most students grasp C++ Files in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now