Use LEFT and RIGHT arrow keys to navigate between flashcards;
Use UP and DOWN arrow keys to flip the card;
H to show hint;
A reads text to speech;
68 Cards in this Set
- Front
- Back
To send output to a file, your program must first connect the file to a (stream)
object of the class ___ . To read input from a file, your program must first connect the file to a (stream) object of the class ___ . |
ofstream
ifstream The classes ifstream and ofstream are defined in the <fstream> library and placed in the std namespace. Thus, to do both file input and file output, your program would contain #include <fstream> using namespace std; or #include <fstream> using std::ifstream; using std::ofstream; |
|
A stream must be declared just as you would declare any other class variable. Thus,
you can declare inStream to be an input stream for a file and outStream to be an output stream for another file as follows: |
ifstream inStream;
ofstream outStream; |
|
Stream variables, such as
inStream and outStream declared above, must each be connected to a file. This is called ___ and is done with the member function named ___ |
opening the file
open For example, suppose you want the input stream inStream connected to the file named infile.txt . Your program must then contain the following before it reads any input from this file: inStream.open("infile.txt"); You can specify a pathname (a directory or folder) when giving the file name. |
|
the following
reads two input numbers from the file connected to inStream and places them in the variables oneNumber and anotherNumber : |
int oneNumber, anotherNumber;
inStream >> oneNumber >> anotherNumber; |
|
the following declares the output stream
outStream and connects it to the file named outfile.txt : |
ofstream outStream;
outStream.open("outfile.txt"); When used with a stream of type ofstream, the member function open will create the output file if it does not already exist. If the output file already exists, the member function open will discard the contents of the file so that the output file is empty after the call to open. |
|
the following
writes two strings and the contents of the variables oneNumber and anotherNumber to the file that is connected to the stream outStream (which in this example is the file named outfile.txt): |
outStream << "oneNumber = " << oneNumber
<< " anotherNumber = " << anotherNumber; |
|
Every file should be closed when your program is finished getting input from the
file or sending output to the file. Closing a file disconnects the stream from the file. A file is closed with a call to the function close. The following lines from the program in Display 12.1 illustrate how to use the function close: |
inStream.close( );
outStream.close( ); Notice that the function close takes no arguments. If your program ends normally but without closing a file, the system will automatically close the file for you. However, it is good to get in the habit of closing files for at least two reasons. First, the system will only close files for you if your program ends normally. If your program ends abnormally due to an error, the file will not be closed and may be left in a corrupted state. If your program closes files as soon as it is finished with them, file corruption is less likely. Second, you may want your program to send output to a file and later read that output back into the program. To do this, your program should close the file after it is finished writing to the file, and then reopen the file with an input stream. (It is possible to open a file for both input and output, but this is done in a slightly different way.) |
|
The member function ___ flushes the output stream so that all output
that may have been buffered is physically written to the file. An invocation of close automatically invokes ___. |
flush
outStream.flush( ); |
|
To append your output to a file named "important.txt", you would use a twoargument
version of open, as illustrated by the following: |
ofstream outStream;
outStream.open("important.txt", ios::app); The second argument ios::app is a defined constant in the class ios. The class ios is defined in the <iostream> library (and also in some other stream libraries). The definition of the class ios is placed in the std namespace, so either of the following will make ios (and hence ios::app) available to your program: #include <iostream> using namespace std; or #include <iostream> using std::ios; |
|
The two statements
ifstream inStream; inStream.open("infile.txt"); can be replaced by the following equivalent line: |
ifstream inStream("infile.txt");
|
|
if the following call to open fails, then the program
will output an error message and end; if the call succeeds, the fail function returns false and the program will continue. |
inStream.open("stuff.txt");
if (inStream.fail( )) { cout << "Input file opening failed.\n"; exit(1); } |
|
___, ___, ___, ___, and ___ work the same for file input as they do for keyboard input; ___ works the same for file output as it does for screen
output. |
get, getline, putback, peek, and ignore
put |
|
Every input-file stream has a member function called ___ that can be used to test
for reaching the end of the input file. |
eof
The function eof takes no arguments, so if the input stream is called fin, then a call to the function eof is written fin.eof( ) |
|
the entire contents of the file connected to
the input stream inStream can be written to the screen with the following while loop: |
inStream.get(next);
while (! inStream.eof( )) { cout << next; inStream.get(next); } |
|
read the file name in from the keyboard, as illustrated by the
following: |
char fileName[16];
ifstream inStream; cout << "Enter file name (maximum of 15 characters):\n"; cin >> fileName; inStream.open(fileName); |
|
you can read the file name into a string variable
and use the string member function c_str( ) to produce the corresponding C-string value for open. The code would be as follows: |
string fileName;
ifstream inStream; cout << "Enter file name:\n"; cin >> fileName; inStream.open(fileName.c_str( )); |
|
If outStream is a file output stream (of type ofstream), you can format
output |
outStream.setf(ios::fixed);
outStream.setf(ios::showpoint); outStream.precision(2); |
|
Floating-point numbers are not written in e-notation. (Setting
this flag automatically unsets the flag ios::scientific.) |
ios::fixed
|
|
Floating-point numbers are written in e-notation. (Setting this
flag automatically unsets the flag ios::fixed.) If neither ios::fixed nor ios::scientific is set, then the system decides how to output each number. |
ios::scientific
|
|
A decimal point and trailing zeros are always shown for floatingpoint
numbers. If it is not set, a number with all zeros after the decimal point might be output without the decimal point and following zeros. |
ios::showpoint
|
|
A plus sign is output before positive integer values.
|
ios::showpos
|
|
If this flag is set and some field-width value is given with a call to
the member function width, then the next item output will be at the right end of the space specified by width. In other words, any extra blanks are placed before the item output. (Setting this flag automatically unsets the flag ios::left.) |
ios::right
|
|
If this flag is set and some field-width value is given with a call to
the member function width, then the next item output will be at the left end of the space specified by width. In other words, any extra blanks are placed after the item output. (Setting this flag automatically unsets the flag ios::right.) |
ios::left
|
|
Integers are output in decimal (base 10) notation.
|
ios::dec
|
|
Integers are output in octal (base 8) notation.
|
ios::oct
|
|
Integers are output in hexadecimal (base 16) notation.
|
ios::hex
|
|
An uppercase E is used instead of a lowercase e in scientific notation
for floating-point numbers. Hexadecimal numbers are output using uppercase letters. |
ios::uppercase
|
|
Shows the base of an output number (leading O for octal, leading
Ox for hexadecimal). |
ios::showbase
|
|
Output streams have other member functions besides precision and setf. One
very commonly used formatting function is width. For example, consider the following call to width made by the stream cout: cout << "Start Now"; cout.width(4); cout << 7 << endl; This code will cause the following line to appear on the screen: |
Start Now 7
This output has exactly three spaces between the letter ’w’ and the number 7. The width function tells the stream how many spaces to use when giving an item as output. In this case the number 7 occupies only one space and width is set to use four spaces, so three of the spaces are blank. If the output requires more space than you specified in the argument to width, then as much additional space as is needed will be used. The entire item is always output, no matter what argument you give to width. |
|
Any flag that is set may be unset. To unset a flag, use the function unsetf. For
example, the following will cause your program to stop including plus signs on positive integers that are output to the stream cout: |
cout.unsetf(ios::showpos);
|
|
A manipulator
is a function that is called in a nontraditional way. Manipulators are placed after the insertion operator << , just as if the manipulator function call were an item to be output. Like traditional functions, manipulators may or may not have arguments. We have already seen one manipulator, endl . This subsection discusses two manipulators called setw and setprecision . The manipulator setw and the member function width (which you have already seen) do exactly the same thing. You call the setw manipulator by writing it after the insertion operator, << , as if it were to be sent to the output stream , and this in turn calls the member function width . For example, the following will output the numbers 10 , 20 , and 30 , using the field widths specified: |
cout << "Start" << setw(4) << 10
<< setw(4) << 20 << setw(6) << 30; |
|
The manipulator
setprecision does the same thing as the member function precision (which you have already seen). However, a call to setprecision is written after the insertion operator, << , in a manner similar to how you call the setw manipulator. For example, the following will output the numbers listed using the number of digits after the decimal point that are indicated by the call to setprecision : |
cout.setf(ios::fixed);
cout.setf(ios::showpoint); cout << "$" << setprecision(2) << 10.3 << endl << "$" << 20.5 << endl; |
|
To use either of the manipulators setw or setprecision, you must include the following
directive in your program: |
#include <iomanip>
using namespace std; or must use one of the other ways of specifying the names and namespace, such as the following: #include <iomanip> using std::setw; using std::setprecision; |
|
Sets flag
|
setf(ios_Flag)
|
|
Unsets flag
|
unsetf(ios_Flag)
|
|
Sets precision for floating-point number
output |
precision(int)
|
|
Returns the current precision setting
|
precision( )
|
|
Sets the output field width; applies
only to the next item output |
width(int)
|
|
Specifies the fill character when the
output field is larger than the value output; the default is a blank |
fill(char)
|
|
If you want to be able to both read and write to a file in C++, you use the stream
class ___ that is defined in the <___> library. The definition of ___ is placed in the std namespace. |
fstream
|
|
Details about opening a file and connecting it to a stream in the class fstream are
basically the same as discussed for the classes ifstream and ofstream, except that fstream has a second argument to open. This second argument specifies whether the stream is used for input, output, or both input and output. For example, a program that does both input and output to a file named "stuff" might start as follows: |
#include <fstream>
using namespace std; int main( ) { fstream rwStream; rwStream.open("stuff", ios::in | ios::out); If you prefer, you may use the following in place of the last two of the previous lines: fstream rwStream("stuff", ios::in | ios::out); After this, your program can read from the file "stuff" using the stream fstream and can also write to the file "stuff" using the same stream. There is no need to close and reopen the file when you change from reading to writing or from writing to reading. Moreover, you have random access for reading and writing to any location in the file. |
|
to position the pointer in the
file connected to the fstream rwStream at the 1000th byte, the invocation would be as follows: |
rwStream.seekp(1000);
|
|
The ___
operator can be used to determine the number of bytes needed for an object of a class or struct. Actually, ___ can be applied to any type, object, or value. It returns the size of its argument in bytes. The operator ___ is part of the core C++ language and requires no include directive or using directive. |
sizeof
|
|
The member function ___ is used to position the get-pointer to indicate where
reading (“getting”) of the next byte will take place. It is completely analogous to seekp. |
seekg
|
|
1. Suppose you are writing a program that uses a stream called fin, which will be connected
to an input file, and a stream called fout, which will be connected to an output file. How do you declare fin and fout? What include directive, if any, do you need to place in your program file? |
1. The streams fin and fout are declared as follows:
ifstream fin; ofstream fout; The include directive that goes at the top of your file is #include <fstream> Since the definitions are placed in the std namespace you should also have one of the following (or something similar): using std::ifstream; using std::ofstream; or using namespace std; |
|
2. Suppose you are continuing to write the program discussed in the previous exercise
and you want your program to take its input from the file stuff1.txt and send its output to the file stuff2.txt. What statements do you need to place in your program in order to connect the stream fin to the file stuff1.txt and to connect the stream fout to the file stuff2.txt? Be sure to include checks to make sure that the openings were successful. |
2. fin.open("stuff1.txt");
if (fin.fail( )) { cout << "Input file opening failed.\n"; exit(1); } fout.open("stuff2.txt"); if (fout.fail( )) { cout << "Output file opening failed.\n"; exit(1); } |
|
3. Suppose that you are still writing the same program that we discussed in the previous
two exercises and you reach the point at which you no longer need to get input from the file stuff1.txt and no longer need to send output to the file stuff2.txt. How do you close these files? |
3. fin.close( );
fout.close( ); |
|
4. Suppose you want to change the program in Display 12.1 so that it sends its output
to the screen instead of the file outfile.txt. (The input should still come from the file infile.txt.) What changes do you need to make to the program? |
4. You need to replace the stream outStream with the stream cout. Note that you do not
need to declare cout, you do not need to call open with cout, and you do not need to close cout. |
|
5. A programmer has read half of the lines in a file. What must the programmer do to
the file to enable reading the first line a second time? |
5. This is “starting over.” The file must be closed and opened again. This action puts the
read position at the start of the file, ready to be read again. |
|
6. What output will be produced when the following lines are executed, assuming the
file list.txt contains the data shown (and assuming the lines are embedded in a complete and correct program with the proper include and using directives)? ifstream ins; ins.open("list.txt"); int count = 0, next; while (ins >> next) { count++; cout << next << endl; } ins.close( ); cout << count; The file list.txt contains the following three numbers (and nothing more): pg. 537 |
6. 1
2 3 3 |
|
7. Write the definition for a void function called toScreen. The function toScreen has
one formal parameter called fileStream, which is of type ifstream. The precondition and postcondition for the function are given below. //Precondition: The stream fileStream has been connected //to a file with a call to the member function open. The //file contains a list of integers (and nothing else). //Postcondition: The numbers in the file connected to //fileStream have been written to the screen one per line. //(This function does not close the file.) |
7. void toScreen(ifstream& fileStream)
{ int next; while (fileStream >> next) cout << next << endl; } |
|
8. What output will be produced when the following lines are executed?
cout << "*"; cout.width(5); cout << 123 << "*" << 123 << "*" << endl; cout << "*" << setw(5) << 123 << "*" << 123 << "*" << endl; |
8. * 123*123*
* 123*123* Each of the spaces contains exactly two blank characters. Notice that a call to width or to setw only lasts for one output item. |
|
9. What output will be produced when the following lines are executed?
cout << "*" << setw(5) << 123; cout.setf(ios::left); cout << "*" << setw(5) << 123; cout.setf(ios::right); cout << "*" << setw(5) << 123 << "*" << endl; |
9. * 123*123 * 123*
Each of the spaces consists of exactly two blank characters. |
|
10. What output will be produced when the following lines are executed?
cout << "*" << setw(5) << 123 << "*" << 123 << "*" << endl; cout.setf(ios::showpos); cout << "*" << setw(5) << 123 << "*" << 123 << "*" << endl; cout.unsetf(ios::showpos); cout.setf(ios::left); cout << "*" << setw(5) << 123 << "*" << setw(5) << 123 << "*" << endl; |
10. * 123*123*
* +123*+123* *123 *123 * There is just one space between the ’*’ and the ’+’ on the second line. Each of the other spaces contains exactly two blank characters. |
|
11. What output will be sent to the file stuff.txt when the following lines are
executed? ofstream fout; fout.open("stuff.txt"); fout << "*" << setw(5) << 123 << "*" << 123 << "*" << endl; fout.setf(ios::showpos); fout << "*" << setw(5) << 123 << "*" << 123 << "*" << endl; fout.unsetf(ios::showpos); fout.setf(ios::left); fout << "*" << setw(5) << 123 << "*" << setw(5) << 123 << "*" << endl; |
11. The output to the file stuff.txt will be exactly the same as the output given in the
answer to Self-Test Exercise 10. |
|
12. What output will be produced when the following line is executed (assuming the line
is embedded in a complete and correct program with the proper include and using directives)? cout << "*" << setw(3) << 12345 << "*" << endl; |
12. *12345*
Notice that the entire integer is output even though this requires more space than was specified by setw. |
|
13. What is the type of the stream cin? What is the type of the stream cout?
|
13. cin is of type istream; cout is of type ostream.
|
|
14. Define a function called copyChar that takes one argument that is an input stream.
When called, copyChar will read one character of input from the input stream given as its argument and will write that character to the screen. You should be able to call your function using either cin or an input-file stream as the argument to your function copyChar. (If the argument is an input-file stream, then the stream is connected to a file before the function is called, so copyChar will not open or close any files.) For example, the first of the following two calls to copyChar will copy a character from the file stuff.txt to the screen, and the second will copy a character from the keyboard to the screen: ifstream fin; fin.open("stuff.txt"); copyChar(fin); copyChar(cin); |
14. void copyChar(istream& sourceFile)
{ char next; sourceFile.get(next); cout << next; } |
|
15. Define a function called copyLine that takes one argument that is an input stream.
When called, copyLine reads one line of input from the input stream given as its argument and writes that line to the screen. You should be able to call your function using either cin or an input-file stream as the argument to your function copyLine. (If the argument is an input-file stream, then the stream is connected to a file before the function is called, so copyLine will not open or close any files.) For example, the first of the following two calls to copyLine will copy a line from the file stuff.txt to the screen, and the second will copy a line from the keyboard to the screen: ifstream fin; fin.open("stuff.txt"); copyLine(fin); copyLine(cin); |
15. void copyLine(istream& sourceFile)
{ char next; do { sourceFile.get(next); cout << next; }while (next != ’\n’); } |
|
16. Define a function called sendLine that takes one argument that is an output stream.
When called, sendLine reads one line of input from the keyboard and outputs the line to the output stream given as its argument. You should be able to call your function using either cout or an output-file stream as the argument to your function sendLine. (If the argument is an output-file stream, then the stream is connected to a file before the function is called, so sendLine will not open or close any files.) For example, the first of the following calls to sendLine will copy a line from the keyboard to the file morestuf.txt, and the second will copy a line from the keyboard to the screen: ofstream fout; fout.open("morestuf.txt"); cout << "Enter 2 lines of input:\n"; sendLine(fout); sendLine(cout); |
16. void sendLine(ostream& targetStream)
{ char next; do { cin.get(next); targetStream << next; }while (next != ’\n’); } |
|
17. Is the following statement true or false? If it is false, correct it. In either event, explain it
carefully. A function written using a parameter of class ifstream or ofstream can be called with istream or ostream arguments, respectively. |
17. False. The situation stated here is the reverse of the correct situation. Any stream that is
of type ifstream is also of type istream, so a formal parameter of type istream can be replaced by an argument of type ifstream in a function call, and similarly for the streams ostream and ofstream. |
|
A stream of type ifstream can be connected to a file with a call to the member
function ___. Your program can then take input from that file. |
open
|
|
A stream of type ofstream can be connected to a file with a call to the member
function ___. Your program can then send output to that file. |
open
|
|
You should use the member function ___ to check whether a call to open was successful.
|
fail
|
|
Stream member functions, such as width, setf, and precision, can be used to format
output. |
These output functions work the same for the stream cout, which is
connected to the screen, and for output streams connected to files. |
|
A function may have formal parameters of a stream type, but they must be call-by reference
parameters. They cannot be call-by-value parameters. |
The type ifstream
can be used for an input-file stream, and the type ofstream can be used for an output-file stream. (See the next summary point for other type possibilities.) |
|
If you use istream (spelled without the ’f’) as the type for an input stream
parameter, then the argument corresponding to that formal parameter can be either the stream cin or an input-file stream of type ifstream (spelled with the ’f’). |
If you use ostream (spelled without the ’f’) as the type for an output stream
parameter, then the argument corresponding to that formal parameter can be either the stream cout, the stream cerr, or an output-file stream of type ofstream (spelled with the ’f’). |
|
The member function ___ can be used to test when a program has reached the end
of an input file. |
eof
|