File I/O
Using Files for Data Storage
Can use files instead of keyboard, monitor screen for program input, output
Allows data to be retained between program runs
Steps:
Open the file
Use the file (read from, write to, or both)
Close the file
General Process
Open File
Check that file opened successfully
Use file (i.e. read/write)
Close File
Files: What is Needed
Use fstream header file for file access
File stream types:
ifstream for input from a file
ofstream for output to a file
fstream for input from or output to a file
Define file stream objects:
ifstream infile;
ofstream outfile;
RAII
Resource Acquisition is Initialization (RAII)
Preferred way of interacting with objects in C++
More on this later when we create our own objects that use dynamic memory.
Prefer to let objects get resources (e.g. open a file) during its initialization.
Prefer to let objects dispose of resources (e.g. close a file) during its destruction.
Automatically happens for objects created in a function.
RAII with File Streams
RAII approach
used in Stroustroup
1. Declare/define file stream and let initialization open file stream.
2. Check if file opened successfully.
3. Use file stream. (i.e. read/write)
4. Implicitly close file.
i.e. Do nothing and let the file close when the object is destroyed.
zyBooks approach
1. Declare then define: a. Declare/define file stream. b. Explicitly open file stream.
2. Check if file opened successfully.
3. Use file stream. (i.e. read/write)
4. Explicitly close file stream.
Sometimes you still need old fashioned way…
Maybe you are running a program that opens multiple files inside a loop
Before Loop begins, declare/define file stream.
Inside loop
1. Open file
2. Check if it opened successfully
3. Use file
4. Close file
Note that here,
open/close happens multiple times for the same file stream object
Letting the User Specify a Filename
The open member function requires that you pass the name of the file as a null-terminated string, which is also known as a C-string.
String literals are stored in memory as null-terminated C-strings, but string objects are not.
string objects have a member function named c_str
It returns the contents of the object formatted as a nullterminated C-string.
Here is the general format of how you call the c_str function: stringObject.c_str()
Last updated
Was this helpful?