Introduction to Computer Science - C++

Reading from a File

        Here is a short program which reads from a file named "data.dat". To access the file we have to create an object of type ifstream. We have called this object ClientFile. Now we can use the > > operator which we recall from cin. In cin this operator reads from the keyboard, here we are using the same operator to read from our object ClientFile which represents the file "data.dat".

#include <iostream> using std::cout; using std::cin; using std::ios; using std::cerr; using std::endl; #include <fstream> using std::ifstream; #include <cstdlib> int main() { int account; char name[40]; double balance; // 1. create object of type ifstream to be used to read the file. // Note that I give the object the file name and a flag ios::in which // means that the file is intended to be read. ifstream ClientFile( "data.dat" , ios::in); cout<< "now we read the file\n"; // 2. we read from the file as represented by the // object ClientFile and use the >> operator // like we used with cin where we read from the keyboard. while (ClientFile >>account >> name >> balance) { // 3. print the data cout << "account number "<<account << " name " <<name <<" balance "<<balance<<endl; } return (1); }

A file must be closed when you are finished reading/writing to it. This will be done automatically when the program exits, but you can do it earlier if you need to by using the command
ClientFile.close();
This may be usefull if you finish with a file before the program exits. In fact, as long as you keep the file open for writing, other programs running at the same time will not be able to open the file for writing. So you may need to close your file when you expect multiple programs to be running. In general, it is just cleaner to close files when you are done with them.

Some other flags for opening files

© Nachum Danzig February 2006