C++ ifstream Class
Example
Use ifstream
to read lines from a file:
// Create a text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();
Definition and Usage
The ifstream
class (short for "input file stream") is used to read from
files.
The ifstream
class is defined in the <fstream>
header file.
To open a file, pass the file path into the constructor:
ifstream MyReadFile("filename.txt");
The ifstream
class has many ways to read data from a file. An easy way is to
use the getline()
function to read all of the characters up to the next line
break and write them into a string.
Output a line of text from the file:
string myText;
getline(MyReadFile, myText);
cout << myText;
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 = MyReadFile.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];
MyReadFile.get(destination, 20);
cout << destination << "\n";
// Stop reading when a '.' is found
MyReadFile.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];
MyReadFile.getline(destination, 20);
cout << destination << "\n";
// Stop reading when a '.' is found
MyReadFile.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 ifstream
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];
MyReadFile.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 = MyReadFile.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];
MyReadFile.getline(destination, 20);
cout << MyReadFile.gcount() << "\n";
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.
ifstream MyReadFile;
MyReadFile.open("filename.txt");
is_open()
The is_open()
method returns true if a file is open and false if there is no
file open.
ifstream MyReadFile;
cout << MyReadFile.is_open(); << "\n"; // Displays 0 because the file is not open
MyReadFile.open("filename.txt");
cout << MyReadFile.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.
MyReadFile.close();
rdbuf()
The rdbuf()
method returns a pointer to the internal filebuf
object which directly handles the
file.
filebuf * buf = MyReadFile.rdbuf();
unget()
The unget()
method moves the file pointer back by one character.
Use the unget()
method to print the same character twice:
char myChar = MyReadFile.get();
cout << myChar << "\n";
MyReadFile.unget();
myChar = MyReadFile.get();
cout << myChar;
seekg()
The seekg(position)
method moves the file pointer to a specified
position relative to the beginning of the file.
MyReadFile.seekg(6)
The seekg(position, origin)
method moves the file pointer
to a specified position in the file relative to an origin. The origin has three possible
values:
ifstream::beg
- The position is relative to the beginning of the file.ifstream::cur
- The position is relative to the current file position.ifstream::end
- The position is relative to the end of the file.
Move the file pointer to different positions:
MyReadFile.seekg(6, ifstream::beg);
cout << MyReadFile.tellg(); << "\n";
MyReadFile.seekg(-3, ifstream::cur);
cout << MyReadFile.tellg(); << "\n";
MyReadFile.seekg(-4, ifstream::end);
cout << MyReadFile.tellg(); << "\n";
tellg()
The tellg()
method returns the current position of the file pointer in the
file.
cout << MyReadFile.tellg();
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
MyReadFile >> variable
It can also be used multiple times to read parts of a file one after another.
MyReadFile >> 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 ifstream 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 ifstream 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 ifstream 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 ifstream
object. The effect of a manipulator remains until
another manipulator changes it.
The following table has a list of manipulators that the ifstream
object can
use.
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;