.txt extension, but any file extension
is acceptable (.cpp files are text files)
fstream to use file I/O classes
#include <fstream>
ifstream class for opening a file for input
nums.txt contained three numbers:
5 1 8
int x, y, z;
ifstream fin;
// Open the file which already exists
fin.open("nums.txt");
// Reads 5, 1, and 8 into x, y, and z
fin >> x >> y >> z;
cout << "Sum of numbers is " << (x + y + z); // 14
// Always close what you open
fin.close();
open("filename") - opens an existing file (must be in the
same directory as the .cpp file)
ifstream >> variable - reads numbers from the given ifstream
into the variable
close() - closes the connection between the file and the variable
good() - returns true if the previous read
operation was successful, false otherwise
int x, total = 0;
ifstream fin;
fin.open("nums.txt");
// Read the first number
fin >> x;
// Loop until there are no numbers left in the file
while (fin.good())
{
total += x;
// Read the next number
fin >> x;
}
cout << "Sum of numbers is " << total;
fin.close();
getline(ifstream, string) to read a string from an
ifstream
fail() - returns true if the prevous read operation
failed to read anything (because no bytes left to read)
!fail() instead of good() is preferred
when reading strings because good() returns false if
the last string in the file does not have a newline char at the end
poem.txt file:
Roses are red, Violets are blue. Here is a poem That doesn't rhyme.Here is a program that reads the
poem.txt file and outputs the contents to the console
string line;
ifstream fin;
// Open the existing poem.txt file
fin.open("poem.txt");
// Read the first line from the file
getline(fin, line);
// Loop until we reach the end of the file
while (!fin.fail())
{
cout << line << endl;
// Get the next line from the file
getline(fin, line);
}
// Done reading from the file
fin.close();
is_open() to determine if open()
was successful - returns true if open failed
ifstream fin;
fin.open("nums.txt");
// Did we fail to open the file?
if (!fin.is_open())
{
cout << "Could not open nums.txt for reading.";
// Terminate the application
exit(0);
}
fail() after attempting to open an input file