- When a program is going to print a lot of data, the data can be sent directly to a file (disk file) instead to the screen
- This file can then be printed or even edited (using the same editor you use to write your programs or make changes to them)
- Directing the output to a file
- Steps to direct the output to a file
1. Include the statement #include <fstream.h>
2. Declare the variable with which the file will be known to the program (e.g.,fout)
3. Specify the name with which the file will be known to the operating system (e.g., "sum.dat")
4. Open the file using the function open (links fout with "sum.dat")
- Directing the output to two different files
#include <fstream.h>
void main()
{
int x, y, sum, prod;
ostream fout1, fout2;
fout1.open("sum.dat");
fout2.open("prod.dat");
x=10;
y=20;
sum=x+y;
prod=x*y;
fout1 << "The sum is " << sum;
fout2 << "The product is " << prod;
}
- Getting the input from a file
- All we have discussed about cout and cin are also valid for fin and fout (e.g., endl, setw, setprecision)
- With an output file, the system checks to see whether the file already exists; if the file does not exist, a new file is created while if the file does exist its contents are erased
- You cannot refer to a file (either for writting or reading data) before you open it first !!
- You cannot read from and write to the same file if fin has been declared using the type ifstream or if fout has been declared using the type ofstream
- The two most common reasons causing input failure are (i) invalid data and (ii) attempting to open an input file that does not exist
- When a program reads data from the keyboard (or from a file), invalid data will cause cin (or fin in our example) to enter the fail state
- Once cin (or fin) has entered the fail state, no data can be read from the input (or file) stream anymore
- Warning: In some cases, an error will be issued while in other cases no error is issued and the program continues execution without reading any input data
i=10;
j=20;
k=30;
cin >> i >> j >> k;
cout << "i: " << i << " j: " << j << " k: " << k;
if we enter the following data: 1234.56 7 89
then the program will produce the output: i: 1234 j: 20 k: 30
- When a program reads data from a file, the file must already exist before the program attempts to open it
* Suppose that you have created the file myfile.dat and that the following statements are in your program
ifstream fin;
fin.open("myfil.dat");
fin >> i >> j >> k;
* The attempt to open "myfil.dat" will fail and fin will enter the fail state (i.e., the variables i, j, and k will keep their old values)
Recommended exercises
- Quick Check excersices 1-5 (page 178)
- 2, 3, 5, 6, 8 (page 179), 9, 11 (page 180)