C++ ofstream Class
Example
Use ofstream
to write to a file:
#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();
}
Definition and Usage
The ofstream
class (short for "output file stream") is used to write into files.
The ofstream
class is defined in the <fstream>
header file.
To open a file, pass the file path into the constructor:
ofstream MyFile("filename.txt");
The <<
insertion operator and a variety of functions can be used to write into the file.
The Insertion Operator
The <<
insertion operator writes a literal value or the contents of a variable into the file.
int year = 2024;
MyFile << year << "\n";
MyFile << "Files can be tricky, but it is fun enough!";
Manipulators
Manipulators change the formatting of the data that is written to the file. They are used with the <<
insertion operator in the same way as literal values and variables.
Except for setw()
, the effect of a manipulator remains until another another manipulator changes it.
Some useful manipulators are shown in the table below.
Manipulator | Description | Example |
---|---|---|
boolalpha |
Writes boolean values as "true" and "false" instead of "1" and "0". | MyFile << boolalpha << false; |
dec |
Represents integers as decimal digits. | MyFile << dec << 12; |
endl |
Writes a newline character. This manipulator also flushes the output buffer which makes it less efficient than printing \n . |
MyFile << "Line 1" << endl << "Line 2"; |
ends |
Writes the \0 null terminating character used to end C-style strings. |
MyFile << "Hello World!" << ends; |
fixed |
Represents floating point numbers with a fixed number of decimal places. The number of decimal places can be established with the setprecision() manipulator. |
MyFile << fixed << 19.99; |
hex |
Represents integers as hexadecimal digits. | MyFile << hex << 12; |
internal |
If a width is specified (using the setw() manipulator), numbers will have their sign left-aligned while the value is right-aligned, other data types will have the output aligned to the right. |
MyFile << setw(10) << internal << -12345; |
left |
If a width is specified (using the setw() manipulator), aligns output to the left. |
MyFile << setw(10) << left << "Hello"; |
noboolalpha |
Used to reset the change made by the boolalpha manipulator. |
MyFile << noboolalpha << false; |
noshowbase |
Used to reset the change made by the showbase manipulator. |
MyFile << hex << noshowbase << 12; |
noshowpoint |
Used to reset the change made by the showpoint manipulator. |
MyFile << noshowpoint << 12345.0; |
noshowpos |
Used to reset the change made by the showpos manipulator. |
MyFile << noshowpos << 12; |
nouppercase |
Used to reset the change made by the uppercase manipulator. |
MyFile << hex << nouppercase << 12; |
oct |
Represents integers as octal digits. | MyFile << oct << 12; |
right |
If a width is specified (using the setw() manipulator), aligns output to the right. |
MyFile << setw(10) << right << "Hello"; |
scientific |
Represents floating point numbers in scientific notation. The number of decimal places can be established with the setprecision() manipulator. |
MyFile << fixed << 19.99; |
setfill() |
Chooses a character to use as padding. Requires the <iomanip> library. |
MyFile << setfill('.') << setw(10) << 19.99; |
setprecision() |
Chooses the precision of floating point numbers. If the fixed or scientific manipulators were used it specifies the number of decimal places, otherwise it specifies the number of significant digits. Requires the <iomanip> library. |
MyFile << setprecision(4) << 12.3456; |
setw() |
Specifies the minimum number of characters wide the next output should be. If the output is not wide enough then padding is added to fill up the remaining space. Requires the <iomanip> library. |
MyFile << setw(10) << "Hello"; |
showbase |
When representing integers as hexadecimal or octal, prefixes the numbers with "0x" or "0" to show their base. | MyFile << hex << showbase << 12; |
showpoint |
Always writes the decimal point for floating point numbers even if it is not needed. | MyFile << showpoint << 12345.0; |
showpos |
Always writes a + sign next to positive numbers. | MyFile << showpos << 12; |
uppercase |
Represents hexadecimal digits and the scientific notation "e" in uppercase. | MyFile << hex << uppercase << 12; |
File Writing Functions
The file writing functions write data into a file and move the file pointer to the first position after the written content.
write()
The write(str, n)
method writes n characters from the char
array str into the file.
char myStr[] = "Hello World!";
MyFile.write(myStr, 5);
put()
The put(c)
method writes the specified character c into the file.
char grade = 'B';
MyFile.put(grade);
File Handling Functions
File handling functions open, close and navigate files.
open()
The open(filepath)
method opens the file at the path specified by filepath. If a file is already open then this method has no effect.
ofstream MyFile;
MyFile.open("filename.txt");
is_open()
The is_open()
method returns true if a file is open and false if there is no file open.
ofstream MyFile;
cout << MyFile.is_open(); << "\n"; // Displays 0 because the file is not open
MyFile.open("filename.txt");
cout << MyFile.is_open(); << "\n"; // Displays 1 because the file is open
close()
The close()
method closes a file. It is good to close a file when you are finished working with it to free up resources.
MyFile.close();
rdbuf()
The rdbuf()
method returns a pointer to the internal filebuf
object which directly handles the file.
filebuf * buf = MyFile.rdbuf();
seekp()
The seekp(position)
method moves the file pointer to a specified position relative to the beginning of the file.
MyFile.seekp(6)
The seekp(position, origin)
method moves the file pointer to a specified position in the file relative to an origin. The origin has three possible values:
ofstream::beg
- The position is relative to the beginning of the file.ofstream::cur
- The position is relative to the current file position.ofstream::end
- The position is relative to the end of the file.
Move the file pointer to different positions:
MyFile.seekp(6, ofstream::beg);
cout << MyFile.tellp(); << "\n";
MyFile.seekp(-3, ofstream::cur);
cout << MyFile.tellp(); << "\n";
MyFile.seekp(-4, ofstream::end);
cout << MyFile.tellp(); << "\n";
tellp()
The tellp()
method returns the current position of the file pointer in the file.
cout << MyFile.tellp();