File I/O in C++ works very similarly to normal I/O (with a few minor added complexities). There are 3 basic file I/O classes in C++: ifstream (derived from istream), ofstream (derived from ostream), and fstream (derived from iostream). These classes do file input, output, and input/output respectively. To use the file I/O classes, you will need to include the fstream.h header.
Unlike the cout, cin, cerr, and clog streams, which are already ready for use, file streams have to be explicitly set up by the programmer. However, this is extremely simple: to open a file for reading and/or writing, simply instantiate an object of the appropriate file I/O class, with the name of the file as a parameter. Then use the insertion (<<) or extraction (>>) operator to read/write to the file. Once you are done, there are several ways to close a file: explicitly call the close() function, or just let the file I/O variable go out of scope (the file I/O class destructor will close the file for you).
File output
To do file output in the following example, we’re going to use the ofstream class. This is extremely straighforward:
If you look in your project directory, you should see a file called Sample.dat. If you open it with a text editor, you will see that it indeed contains two lines we wrote to the file.
Note that it is also possible to use the put() function to write a single character to the file.
File input
Now, we’ll take the file we wrote in the last example and read it back in from disk. Note that ifstream returns a 0 if we’ve reached the end of the file (EOF). We’ll use this fact to determine how much to read.
This produces the result:
This produces the result:
Output in C++ may be buffered. This means that anything that is output to a file stream may not be written to disk immediately. Instead, several output operations may be batched and handled together. This is done primarily for performance reasons. When a buffer is written to disk, this is called flushing the buffer. One way to cause the buffer to be flushed is to close the file — the contents of the buffer will be flushed to disk, and then the file will be closed.
Buffering is usually not a problem, but in certain circumstance it can cause complications for the unwary. The main culprit in this case is when there is data in the buffer, and then program terminates immediately (either by crashing, or by calling exit()). In these cases, the destructors for the file stream classes are not executed, which means the files are never closed, which means the buffers are never flushed. In this case, the data in the buffer is not written to disk, and is lost forever. This is why it is always a good idea to explicitly close any open files before calling exit().
It is possible to flush the buffer manually using the ostream flush() function. Calling flush() can be useful to ensure the contents of the buffer are written to disk immediately, just in case the program crashes.
File modes
What happens if we try to write to a file that already exists? Running the output example again shows that the original file is completely overwritten each time the program is run. What if, instead, we wanted to append some more data to the end of the file? It turns out that the file stream constructors take an optional second parameter that allows you to specify information about how the file should be opened. This parameter is called mode, and the valid flags that it accepts live in the Ios class.
It is possible to specify multiple flags by bitwise ORing them together (using the | operator). Note that ios::in and ios::out are already defaults for the ifstream and ofstream classes respectively. If you opt to use fstream (which can do both input and output), you explicitly have to pass in ios::in and/or ios::out depending on which mode you’d like to use.
Let’s write a program that appends two more lines to the Sample.dat file we previously created:
Now if we take a look at Sample.dat (using one of the above sample programs that prints its contents, or loading it in a text editor), we will see the following:
Just like it is possible to explicitly close a file stream using close(), it’s also possible to explicitly open a file stream using open(). open() works just like the file stream constructors — it takes a file name and an optional file mode.
For example:
Unlike the cout, cin, cerr, and clog streams, which are already ready for use, file streams have to be explicitly set up by the programmer. However, this is extremely simple: to open a file for reading and/or writing, simply instantiate an object of the appropriate file I/O class, with the name of the file as a parameter. Then use the insertion (<<) or extraction (>>) operator to read/write to the file. Once you are done, there are several ways to close a file: explicitly call the close() function, or just let the file I/O variable go out of scope (the file I/O class destructor will close the file for you).
File output
To do file output in the following example, we’re going to use the ofstream class. This is extremely straighforward:
01 | #include <fstream> |
02 | #include <iostream> |
03 |
04 | int main() |
05 | { |
06 | using namespace std; |
07 |
08 | // ofstream is used for writing files |
09 | // We'll make a file called Sample.dat |
10 | ofstream outf( "Sample.dat" ); |
11 |
12 | // If we couldn't open the output file stream for writing |
13 | if (!outf) |
14 | { |
15 | // Print an error and exit |
16 | cerr << "Uh oh, Sample.dat could not be opened for writing!" << endl; |
17 | exit (1); |
18 | } |
19 |
20 | // We'll write two lines into this file |
21 | outf << "This is line 1" << endl; |
22 | outf << "This is line 2" << endl; |
23 |
24 | return 0; |
25 |
26 | // When outf goes out of scope, the ofstream |
27 | // destructor will close the file |
28 | } |
Note that it is also possible to use the put() function to write a single character to the file.
File input
Now, we’ll take the file we wrote in the last example and read it back in from disk. Note that ifstream returns a 0 if we’ve reached the end of the file (EOF). We’ll use this fact to determine how much to read.
01 | #include <fstream> |
02 | #include <iostream> |
03 | #include <string> |
04 |
05 | int main() |
06 | { |
07 | using namespace std; |
08 |
09 | // ifstream is used for reading files |
10 | // We'll read from a file called Sample.dat |
11 | ifstream inf( "Sample.dat" ); |
12 |
13 | // If we couldn't open the output file stream for reading |
14 | if (!inf) |
15 | { |
16 | // Print an error and exit |
17 | cerr << "Uh oh, Sample.dat could not be opened for reading!" << endl; |
18 | exit (1); |
19 | } |
20 |
21 | // While there's still stuff left to read |
22 | while (inf) |
23 | { |
24 | // read stuff from the file into a string and print it |
25 | std::string strInput; |
26 | inf >> strInput; |
27 | cout << strInput << endl; |
28 | } |
29 |
30 | return 0; |
31 |
32 | // When inf goes out of scope, the ifstream |
33 | // destructor will close the file |
34 | } |
This is line 1 This is line 2Hmmm, that wasn’t quite what we wanted. Remember that the extraction operator deals with “formatted output”, and breaks on whitespace. In order to read in entire lines, we’ll have to use the getline() function.
01 | #include <fstream> |
02 | #include <iostream> |
03 | #include <string> |
04 |
05 | int main() |
06 | { |
07 | using namespace std; |
08 |
09 | // ifstream is used for reading files |
10 | // We'll read from a file called Sample.dat |
11 | ifstream inf( "Sample.dat" ); |
12 |
13 | // If we couldn't open the input file stream for reading |
14 | if (!inf) |
15 | { |
16 | // Print an error and exit |
17 | cerr << "Uh oh, Sample.dat could not be opened for reading!" << endl; |
18 | exit (1); |
19 | } |
20 |
21 | // While there's still stuff left to read |
22 | while (inf) |
23 | { |
24 | // read stuff from the file into a string and print it |
25 | std::string strInput; |
26 | getline(inf, strInput); |
27 | cout << strInput << endl; |
28 | } |
29 |
30 | return 0; |
31 |
32 | // When inf goes out of scope, the ifstream |
33 | // destructor will close the file |
34 | } |
This is line 1 This is line 2Buffered output
Output in C++ may be buffered. This means that anything that is output to a file stream may not be written to disk immediately. Instead, several output operations may be batched and handled together. This is done primarily for performance reasons. When a buffer is written to disk, this is called flushing the buffer. One way to cause the buffer to be flushed is to close the file — the contents of the buffer will be flushed to disk, and then the file will be closed.
Buffering is usually not a problem, but in certain circumstance it can cause complications for the unwary. The main culprit in this case is when there is data in the buffer, and then program terminates immediately (either by crashing, or by calling exit()). In these cases, the destructors for the file stream classes are not executed, which means the files are never closed, which means the buffers are never flushed. In this case, the data in the buffer is not written to disk, and is lost forever. This is why it is always a good idea to explicitly close any open files before calling exit().
It is possible to flush the buffer manually using the ostream flush() function. Calling flush() can be useful to ensure the contents of the buffer are written to disk immediately, just in case the program crashes.
File modes
What happens if we try to write to a file that already exists? Running the output example again shows that the original file is completely overwritten each time the program is run. What if, instead, we wanted to append some more data to the end of the file? It turns out that the file stream constructors take an optional second parameter that allows you to specify information about how the file should be opened. This parameter is called mode, and the valid flags that it accepts live in the Ios class.
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 |
Let’s write a program that appends two more lines to the Sample.dat file we previously created:
01 | int main() |
02 | { |
03 | using namespace std; |
04 |
05 | // We'll pass the ios:app flag to tell the ofstream to append |
06 | // rather than rewrite the file. We do not need to pass in ios::out |
07 | // because ofstream defaults to ios::out |
08 | ofstream outf( "Sample.dat" , ios::app); |
09 |
10 | // If we couldn't open the output file stream for writing |
11 | if (!outf) |
12 | { |
13 | // Print an error and exit |
14 | cerr << "Uh oh, Sample.dat could not be opened for writing!" << endl; |
15 | exit (1); |
16 | } |
17 |
18 | outf << "This is line 3" << endl; |
19 | outf << "This is line 4" << endl; |
20 |
21 | return 0; |
22 |
23 | // When outf goes out of scope, the ofstream |
24 | // destructor will close the file |
25 | } |
This is line 1 This is line 2 This is line 3 This is line 4Explicitly opening files using open()
Just like it is possible to explicitly close a file stream using close(), it’s also possible to explicitly open a file stream using open(). open() works just like the file stream constructors — it takes a file name and an optional file mode.
For example:
1 | ofstream outf( "Sample.dat" ); |
2 | outf << "This is line 1" << endl; |
3 | outf << "This is line 2" << endl; |
4 | outf.close(); // explicitly close the file |
5 |
6 | // Oops, we forgot something |
7 | outf.open( "Sample.dat" , ios::app); |
8 | outf << "This is line 3" << endl; |
9 | outf.close(); |
No comments:
Post a Comment