读取文本数据的时候,其相应的流程与写入颇为相似,但也有一些区别,毕竟是两个不同的功能。
1.添加必须的头文件:#include <fstream> 、#include <cstdlib>。
2.定义相应的数组,用于存储文件的名称。
3.定义相应的变量,用于存储文件写入的数据。
4.创建一个ifstream对象。
5.将ifstream与文本文件进行关联。
6.测试文件打开是否正常。
7.使用ifstream对象和<<运算符进行数据写入。
8.使用完ifstream对象后关闭。以一个遍历文本所有数据,并计算所占字符的程序作为实例:
#include <iostream>
#include <fstream> // file I/O support
#include <cstdlib> // support for exit
const int SIZE = 60;
int main()
{
using namespace std;
char filename[SIZE];
char ch;
ifstream inFile; // object for handing file input
cout << "Enter name of data file: ";
cin.getline(filename,SIZE);
inFile.open(filename); // associate inFile with a file
if(!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 read
inFile >> ch;
while(inFile.good()) // while input good not at EOF
{
sum++;
inFile >> ch;
}
cout << sum << " characters in " << filename << endl;
inFile.close(); // done with the file
return 0;
}在遍历文件中数据时,good()方法是个不错的选择,因为failed(),eof(),bad()在遍历时都有自己的奇葩之处(具体请百度,不做详解)。
原文:http://blog.csdn.net/wzqnls/article/details/42169989