Ofstream – Write to a file
ifstream – read a file
• https://www.geeksforgeeks.org/file-handling-
c-classes/
fstream
• C++ also provides file stream classes to perform
input and output operations on files that are
defined inside <fstream> header file.
File Handling Operations
There are mainly three main steps in file handling:
• Opening a File
• Read/Write Operations
• Closing a File
Opening a File
• Before reading from or writing to a file, we first
need to open it. Opening a file loads that file in
the RAM.
• In C++, we open a file by creating a stream to it
using the fstream class that represent the file
stream i.e. stream for input and output to the file.
fstream str("filename.ext", mode);
where,
str: name of the file stream object.
filename: Name of the file to be opened.
mode: Represents the way in which we are going to
interact with the file.(file opening mode)
File Opening Modes
• File opening mode indicate file is opened for reading, writing, or
appending. Below is the list of all file modes in C++:
Mode Description
ios::in File open for reading. If file does not exists,
File open for writing: the internal stream buffer
ios::out
supports output operations.
Operations are performed in binary mode rather
ios::binary
than text.
ios::ate The output position starts at the end of the file.
All output operations happen at the end of the file,
ios::app
appending to its existing contents.
Any contents that existed in the file before it is open
ios::trunc
are discarded.
Examples
• If we want to open the file for reading, we use
the following opening mode:
fstream filein("file.txt", ios::in);
• If we want to open the file for writing, we use the
following:
fstream fileout("file.txt", ios::out);
• These modes can also be combined using OR
operator (|). We can open the file stream in both
read and write mode as shown below:
fstream str("file.txt", ios::in | ios::out);
Other File Streams
• fstream is not the only file stream provided by
C++. There are two more specialized streams:
• ifstream: Stands for input file stream. It is
equivalent to open fstream in ios::in mode.
• ofstream: Stands for output file stream. It is
equivalent to opening fstream in ios::out mode.
ifstream filein("file.txt");
Similarly, for output:
ofstream fileout("file.txt");
Write Data to File
• Once the file is opened in the write mode using
either fstream or ofstream, we can perform the
write operation in similar way as with cout
using << operator.
int main() {
// Open a file
ofstream file("GFG.txt");
// Write the string to the file
file << "Welcome to GeeksforGeeks.";
return 0;
}
Read Data from File
• Once the file is opened in the read mode using either fstream or
ifstream, we can perform the write operation in similar way as
with cin using >> operator.
int main() { int main() {
// Open a file in read mode // Open a file in read mode
ifstream file("GFG.txt"); ifstream file("GFG.txt");
string s; string s;
// Read string from the file // Read string from the file
file >> s; getline(file, s);
cout << "Read String: " << s; cout << "Read String: " << s;
return 0; return 0;
} }
Output
Output
Read String : Welcome
Read String: Welcome to GeeksforGeeks.
Closing the File
• In C++, the files are closed using the close() member function that is
present in all file streams.
int main() {
// Open a file in read mode
ifstream file("GFG.txt");
string s;
// Read string from the file
getline(file, s);
cout << "Read String: " << s;
// Close the file
file.close();
return 0;
}
Handling Binary Files
• In C++, we can also handle binary files, which
store data in raw format. To read and write
binary data, must use the ios::binary flag when
creating/opening a binary file.
Write into Binary File
• To write data to a binary file, we first need to open or create the
file in ios::binary mode.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main() {
string str = "Welcome to GeeksForGeeks";
// Open a binary file for writing
ofstream file("fileBin.bin", ios::binary);
// Check if the file is open
if (!file) {
cerr << "Error opening the file for writing.";
return 1;
}
// Write the length of the string (size) to file first
size_t strLength = str.length();
file.write(reinterpret_cast<const char*>(&strLength),
sizeof(strLength));
// Write the string to the binary file
file.write(str.c_str(), strLength);
// Close the file
file.close();
We can use ifstream to read the content
We can use ofstream to write the content
I/O Manipulation
• Manipulators are helping functions that can modify the input or
output stream. They can be included in the I/O statement to alter
the format parameters of a stream. They are defined inside
<iomanip> and some are also defined inside <iostream> header
file.
• For example, if we want to print the hexadecimal value of 100
then we can print it as:
cout << setbase(16) << 100
Manipulator Description Header File
Inserts a newline and
endl flushes the output stream. iostream
Flushes the output stream
flush manually. iostream
Sets the width of the next
setw(x) output field to x. iomanip
Sets the precision for
setprecision(x) floating-point numbers to iomanip
x.
Displays numbers in fixed-
fixed point notation. iomanip
scientific Displays numbers in iomanip
scientific notation.
showpoint Forces the display of the iomanip
decimal point.
Hides the decimal point
noshowpoint unless necessary. iomanip