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
All contributors
- garanews209 total contributions
- christian.dinh2481 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions
- Anonymous contributorAnonymous contributor9 total contributions
- Prince2517 total contributions
- Christine_Yang269 total contributions
- garanews
- christian.dinh
- Anonymous contributor
- Anonymous contributor
- Prince25
- Christine_Yang
Looking to contribute?
- 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.