Files
Computers use file systems to store and retrieve data. Each file is an individual container of related information.
The fstream
library, short for “file stream”, enables working with files in C++. To use the fstream
library in the C++ program, include both the standard <iostream>
and the <fstream>
header files in the C++ program:
#include <iostream>#include <fstream>
There are three classes included in the fstream
library, which are used to create, write or read files:
ofstream
(“output file stream”): Create files and write to files.ifstream
(“input file stream”): Read from files.fstream
: A combination ofofstream
andifstream
(create, read, and write 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 (<<
). For example:
#include <iostream>#include <fstream>int main() {// Create and open a text filestd::ofstream MyFile("journal.txt");// Write to the fileMyFile << "Today is the greatest\n";MyFile << "Day I've ever known";// Close the fileMyFile.close();}
In the same folder, there should be a new text file called journal.txt
. There should be two lines of text inside:
Today is the greatest
Day I've ever known
Read a File
To read from a file, use either the ifstream
or fstream
class, and the name of the file.
Note: A
while
loop is used together with thegetline()
function (which belongs to theifstream
class) to read the file line by line, and to print the content of the file:
#include <iostream>#include <fstream>int main() {// Create a text string, which is used to output the text filestd::string myText;// Read from the text filestd::ifstream MyReadFile("journal.txt");// Output the file line by linewhile (getline (MyReadFile, myText)) {std::cout << myText << "\n";}// Close the fileMyReadFile.close();}
The output would be:
Today is the greatestDay I've ever known
Appending to a File
In some cases, you may want to append text to an existing file instead of overwriting its content. To do this, you can open the file in append mode using the std::ios::app
flag with ofstream
or fstream
. Here’s an example:
#include <iostream>#include <fstream>int main() {// Open the file in append modestd::ofstream MyFile("journal.txt", std::ios::app);// Append text to the fileMyFile << "\nSmashing Pumpkins lyrics\n";// Close the fileMyFile.close();}
The file journal.txt
will now contain:
Today is the greatestDay I've ever knownSmashing Pumpkins lyrics
Checking if a file exists
Before opening a file, checking if the file exists is a good practice. This can prevent issues like reading a file that doesn’t exist. You can use the .is_open()
function for this:
#include <iostream>#include <fstream>int main() {std::ifstream MyFile("journal.txt");// Check if the file opened successfullyif (MyFile.is_open()) {std::cout << "File opened successfully.\n";} else {std::cout << "File does not exist.\n";}// Close the fileMyFile.close();}
If the file journal.txt
exists, the output will be:
File opened successfully.
If the file journal.txt
does not exist, the output will be:
File does not exist.
All contributors
- garanews
- christian.dinh
- Anonymous contributor
- bhagyamudgal
- Anonymous contributor
- Prince25
- Christine_Yang
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours