The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home File Input/Output and pmatrices File Input | ||
File Input
To get data from a file, we have to create a stream that flows from the file into the program. We can do that using the ifstream constructor. ifstream infile ("file-name");The argument for this constructor is a string that contains the name of the file you want to open. The result is an object named infile that supports all the same operations as cin, including >> and getline. int x;pstring line; infile >> x; // get a single integer and store in x getline (infile, line); // get a whole line and store in line
There are member functions for ifstreams that check the status of the input stream; they are called good, eof, fail and bad. We will use good to make sure the file was opened successfully and eof to detect the "end of file." Whenever you get data from an input stream, you don't know whether the attempt succeeded until you check. If the return value from eof is true then we have reached the end of the file and we know that the last attempt failed. Here is a program that reads lines from a file and displays them on the screen: pstring fileName = ...;ifstream infile (fileName.c_str()); if (infile.good() == false) { cout << "Unable to open the file named " << fileName; exit (1); } while (true) { getline (infile, line); if (infile.eof()) break; cout << line << endl; } The function c_str converts an pstring to a native C string. Because the ifstream constructor expects a C string as an argument, we have to convert the pstring. Immediately after opening the file, we invoke the good function. The return value is false if the system could not open the file, most likely because it does not exist, or you do not have permission to read it. The statement while(true) is an idiom for an infinite loop. Usually there will be a break statement somewhere in the loop so that the program does not really run forever (although some programs do). In this case, the break statement allows us to exit the loop as soon as we detect the end of file. It is important to exit the loop between the input statement and the output statement, so that when getline fails at the end of the file, we do not output the invalid data in line.
|
||
Home File Input/Output and pmatrices File Input |