File Input And Output
Table of Contents
|
Introduction
The fstream header defines three types to support file IO:
- ifstream, derived from istream, reads from a file.
- ofstream, derived from ostream, writes to a file.
- fstream, derived from iostream, reads and writes the same file.
When we want to read or write a file, we must define our own objects, and bind them to the desired files.
File Output
- use of the ofstream class
Example 1
#include <fstream> #include <iostream> #include <cstdlib> int main() { using namespace std; // ofstream is used for writing files // We'll make a file called Sample.dat ofstream outf("Sample.dat"); // If we couldn't open the output file stream for writing if (!outf) { // Print an error and exit cerr << "Uh oh, Sample.dat could not be opened for writing!" << endl; exit(0); } // We'll write two lines into this file outf << "This is line 1" << endl; outf << "This is line 2" << endl; return 0; // When outf goes out of scope, the ofstream // destructor will close the file }
File Input
- Use of ifstream class
Example 2
#include <fstream> #include <iostream> #include <string> #include <cstdlib> int main() { using namespace std; // ifstream is used for reading files // We'll read from a file called Sample.dat ifstream inf("Sample.dat"); // If we couldn't open the input file stream for reading if (!inf) { // Print an error and exit cerr << "Uh oh, Sample.dat could not be opened for reading!" << endl; exit(1); } // While there's still stuff left to read while (inf) { // read stuff from the file into a string and print it std::string strInput; getline(inf, strInput); cout << strInput << endl; } return 0; // When inf goes out of scope, the ifstream // destructor will close the file }
Files Modes
- File stream constructors take an optinal second parameter that allows the programmer to specify information about how the file should be opened. This is called mode.
Ios file mode | Meaning |
---|---|
app | Opens the file in append mode |
ate | Seeks to the end of the file before reading/writing |
binary | Opens the file in binary mode (instead of text mode) |
in | Opens the file in read mode (default for ifstream) |
nocreate | Opens the file only if it already exists |
noreplace | Opens the file only if it does not already exist |
out | Opens the file in write mode (default for ofstream) |
trunc | Erases the file if it already exists |
Random File I/O
The file pointer
- Each file stream class contains a file pointer that is used to keep track of the current read/write position within the file.
- When something is read from or written to a file, the reading/writing happens at the file pointer’s current location.