When reading text data, its corresponding process and write quite similar, but there are some differences, after all, is two different functions.
1. Add the necessary header files: #include <fstream>, #include <cstdlib>.
2. Define the appropriate array to store the name of the file.
3. Define the appropriate variables to store the data written by the file.
4. Create a Ifstream object.
5. Associate the Ifstream with a text file.
6. Test whether the file is open properly.
7. Write data using the Ifstream object and the << operator.
8. Close when you are finished using the Ifstream object.
As an example, a program that iterates through all the data and computes the characters is used as an instance:
#include <iostream> #include <fstream>//file I/O support#include <cstdlib>//support for Exitconst int SIZE = 60;int Main () {using namespace Std;char Filename[size];char ch;ifstream infile;//object for handing file inputcout << "Enter Name of data file:"; Cin.getline (filename,size); Infile.open (filename);//Associate InFile with a Fileif (! Infile.is_open ())//failed to open file{cout << ' Could not open the file ' << filename << endl;cout < < "program terminating.\n"; exit (exit_failure);} int sum = 0;//number of items Readinfile >> ch;while (Infile.good ())//While input good not at Eof{sum++;infile > > ch;} cout << sum << "characters in" << filename << endl;infile.close ();//Done with the Filereturn 0; }
when the test file is open normally, if the open fails, it is necessary to terminate the program's operation, here to use the # include <cstdlib> header file, the corresponding statement in the program EXIT (exit_failure); with it, Mother no longer have to worry about the file open failed to do.
When traversing data in a file, the good () method is a good choice, because failed (), EOF (), bad () in the traversal has its own wonderful place (specifically please Baidu, do not do the detailed).
C + + Text data read