C++ fstream Class
Example
Use fstream
to read and write to a file:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
fstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!";
// Read from the file
string myText;
getline(MyFile, myText);
cout << myText;
// Close the file
MyFile.close();
}
Definition and Usage
The fstream
class (short for "file stream") is used to read and write into files.
The fstream
class is defined in the <fstream>
header file.
Unlike the ofstream
class, the fstream
class does not create new files, it only writes to existing ones.
To open a file, pass the file path into the constructor:
fstream MyFile("filename.txt");
The fstream
class has a variety of functions for reading and writing files which are listed below.
File Pointer Functions
File pointers are internal variables which indicate where in the file to read or write.
File pointer functions are used to manipulate file pointers. There are functions for both a read file pointer and a write file pointer, but the fstream
class uses the same pointer for both actions, so changing one of them also changes the other one.
seekg()
The seekg(position)
method moves the read file pointer to a specified position relative to the beginning of the file.
MyFile.seekg(6)
The seekg(position, origin)
method moves the read file pointer to a specified position in the file relative to an origin. The origin has three possible values:
fstream::beg
- The position is relative to the beginning of the file.fstream::cur
- The position is relative to the current file position.fstream::end
- The position is relative to the end of the file.
Move the read file pointer to different positions:
MyFile.seekg(6, fstream::beg);
cout << MyFile.tellg() << "\n";
MyFile.seekg(-3, fstream::cur);
cout << MyFile.tellg() << "\n";
MyFile.seekg(-4, fstream::end);
cout << MyFile.tellg() << "\n";
tellg()
The tellg()
method returns the current position of the file pointer in the file.
cout << MyFile.tellg();
seekp()
The seekp(position)
method moves the write file pointer to a specified position relative to the beginning of the file.
MyFile.seekp(6)
The seekp(position, origin)
method moves the write file pointer to a specified position in the file relative to an origin. The origin has three possible values:
fstream::beg
- The position is relative to the beginning of the file.fstream::cur
- The position is relative to the current file position.fstream::end
- The position is relative to the end of the file.
Move the write file pointer to different positions:
MyFile.seekp(6, fstream::beg);
cout << MyFile.tellp() << "\n";
MyFile.seekp(-3, fstream::cur);
cout << MyFile.tellp() << "\n";
MyFile.seekp(-4, fstream::end);
cout << MyFile.tellp() << "\n";
tellp()
The tellp()
method returns the current position of the write file pointer in the file.
cout << MyFile.tellp();
File Reading Functions
File reading functions extract characters from a file and move the file pointer.
get()
The get()
method reads a single character from a file and returns its ASCII value as an int
value. Convert it to a char
type to see the character. The file pointer is moved to the next character in the file.
char myChar = MyFile.get();
cout << myChar;
The get(destination, size, delimiter)
method writes up to size characters to the destination with data read from the file. It stops reading as soon as it reaches a line break, end of file, or an optional character given by the delimiter parameter. The value written in destination always ends with a \0
null terminating character. This method moves the file pointer to the line break or delimiter where it stopped reading.
char destination[20];
MyFile.get(destination, 20);
cout << destination << "\n";
// Stop reading when a '.' is found
MyFile.get(destination, 20, '.');
cout << destination << "\n";
getline()
The getline(destination, size, delimiter)
method is the same as the get(destination, size, delimiter)
method, except that the line break or delimiter is discarded and the file pointer is moved to the character that follows it.
char destination[20];
MyFile.getline(destination, 20);
cout << destination << "\n";
// Stop reading when a '.' is found
MyFile.getline(destination, 20, '.');
cout << destination << "\n";
There is a similar getline(stream, destination, delimiter)
function which reads all of the characters up to the next line break (or optional delimiter) from the file specified by the fstream
object in the stream parameter and writes them into the string specified by destination.
string destination;
getline(MyFile, destination);
cout << destination << "\n";
// Stop reading when a '.' is found
getline(MyFile, destination, '.');
cout << destination << "\n";
read()
The read(destination, n)
method reads n characters from the file and writes them into the char
array specified by the destination parameter. Unlike other functions, it does not stop reading at line breaks and it does not add a null terminating character to the data.
char destination[20];
MyFile.read(destination, 19);
destination[20] = '\0'; // Make sure it ends with a null terminating character
cout << destination << "\n";
peek()
The peek()
method reads a single character from a file and returns its ASCII value as an int
value. Convert it to a char
type to see the character. Unlike the get()
method, this method does not move the file pointer.
char myChar = MyFile.peek();
cout << myChar;
gcount()
The gcount()
method returns the number of characters extracted from the file by most recently called file reading method.
char destination[20];
MyFile.getline(destination, 20);
cout << MyFile.gcount() << "\n";
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 and moves the file pointer forward by n characters.
char myStr[] = "Hello World!";
MyFile.write(myStr, 5);
put()
The put(c)
method writes the specified character c into the file and moves the file pointer forward by one character.
char grade = 'B';
MyFile.put(grade);
File Handling Functions
File handling functions open and close 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.
fstream 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();
The Extraction Operator
The >>
extraction operator reads a number of characters from the current position in the file, interprets them and writes the interpreted value into a variable. Then the file pointer is moved to the next character which has not yet been read. The way that the characters are interpreted depends on the data type of the variable.
Syntax
MyFile >> variable
It can also be used multiple times to read parts of a file one after another.
MyFile >> variable1 >> variable2 >> variable3
The >>
extraction operator starts by skipping over whitespace characters (spaces, tabs and line breaks) until it reaches the first character that is not whitespace. After that, it follows the rules shown in the following table based on the data type of the variable.
Data Type | Description | Examples |
---|---|---|
int long short
|
Reads a sequence of digits and interprets them as an integer. The sequence may be preceded by a sign ("+" or "-"). It stops reading at the first character that is not a digit. If a valid sequence is not found the ifstream object will fail and stop reading further.
|
15 |
bool |
Reads an integer in the same way as described above and then interprets 0 as false and 1 as true. Any other integer value will be interpreted as true but the ifstream object will fail and stop reading further.The boolalpha manipulator described in the next section completely changes this behavior.
|
0 |
float double
|
Reads a valid sequence of characters and interprets them as a floating point number. A valid sequence has at least one digit, it can be preceded by a sign ("+" or "-") and it can be followed by a decimal point and decimal digits. Scientific notation (a number followed by "e" or "E" and some digits) can also be used. If a valid sequence is not found the fstream object will fail and stop reading further.
|
5 |
char
|
Reads a single character from the file. If the file pointer is at the end of the file the fstream object will fail and stop reading further.
|
B |
string char *
|
Reads all of the characters up to the next whitespace (space, tab or line break), null terminating character or end of file. The variable will have a \0 null terminating character added to the value.If the file pointer is already at a null terminating character or at the end of the file the fstream object will fail and stop reading further.
|
Hello |
Manipulators
A manipulator can be used in place of a variable. When manipulators are used they change how data is interpreted by the fstream
object. The effect of a manipulator remains until another manipulator changes it.
The following table has a list of manipulators that can be used with the >>
extraction operator.
Manipulator | Description |
---|---|
noskipws |
Instead of skipping over whitespace characters the >> extraction operator will read them. This is mainly useful for char type variables because with other data types it stops reading when it runs into whitespace. |
skipws |
Resets the change made by the noskipws manipulator. |
ws |
Moves the file pointer to the next position of the file that does not have whitespace. |
hex |
Expect hexadecimal representations (digits 0 to 9 and A to F) of numbers when using integer variables. |
oct |
Expect octal representations (digits 0 to 7) of numbers when using integer variables. |
dec |
Expect decimal representations (digits 0 to 9) of numbers when using integer variables. This resets the change made by the hex and oct manipulators. |
boolalpha |
When reading data for a boolean variable, instead of looking for an integer it looks for the character sequence "true" or "false". |
noboolalpha |
Resets the change made by the boolalpha manipulator. |
Example
Use manipulators to change how data is interpreted:
bool myBool;
int myInt;
// Interpret character sequences "true" and "false" as boolean values
MyFile >> boolalpha >> myBool;
// Revert to reading booleans normally
MyFile >> noboolalpha;
// Read hexadecimal numbers from the file and interpret them as integers
MyFile >> hex >> myInt;
// Revert to reading integers normally
MyFile >> dec;
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.
The table below shows a list of useful manipulators:
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; |