The purpose of this quiz is to give you a chance to focus your knowledge of simple file handling in C++.
Before you can open a connection to a file stream, you must do three things:
Once you are ready, you'll need to do two things to make a connection to a user's file:
When opening a file connection, make sure the stream connected successfully to the file by:
What functions/operations can you use to get data from an ifstream variable?
>>, getline, peek, etc.
What functions/operations can you use to put data into an ofstream variable?
<<, setw, flush, etc.
What is the type of getline's first argument that it can be used to read from either cin or an ifstream variable?
istream & is compatible with both the console stream
cin and any ifstream variable.
What type should you use to allow a function to 'display' to either cout or an ofstream variable?
ostream & is compatible with both the console stream
cout and any ofstream variable.
Show pseudocode for a good loop to read until the end of a file is reached.
peeky read
while ( ! eof )
{
read data
process data
peeky read
}
The peeky read should be a ws extraction when extracting data in the loop
or an actual peek when getline is being used to gather data in the loop.
Show a good loop to open an input file the user specifies.
prompt for and read file's name (getline)
attempt to open file
while ( ! file )
{
close/clear the ifstream
print an error message
prompt for and read file's name (getline)
attempt to open file
}
How does this get complicated when the file is an output file? What else can go wrong besides those things that happen with input files?
Opening an output file automatically erases any content the file may
contain. This can be disastrous for the user! To avoid this, we need
to take advantage of the input file's ability to open an existing file
but to fail when a file doesn't exist.
To alleviate this issue, we can open the file name as an input file and,
if successful, offer to the user to open it for appending instead of
plain output.