1.首先说明一下几个类的关系:
如图:ios_base是ios类的基类,然后分别派生出 istream 和 ostream 输入输出类,而iostream 类由继承了 istream 和 ostream 的输入输出。
ifstream 类继承了istream ,ofstream 继承了 ostream类。
2.文件打开方式:
ofstream out; //输出流指针out
ifstream in; //输入流指针in
out.open("file.txt"); //以输出的方式打开文件 file.txt
wrtie_file(out); //write_file是用户自己写的一个函数,用于操作 out指针指向的文件
out.close(); //操作完之后一定要关闭流指针。否则不能用 其他流指针打开该文件,如 输入流指针
//不调用 close()函数,就无法使其他流指针或者说其他进程访问这个文件
in.open("file.txt"); //以输入的方式打开文件 file.txt
read_file(in); //read_file是用户自己写的一个函数,用于操作 in指针指向的文件
in.close(); //关闭输入流指针
/*-----------再说一种方式-------------*/
如:
ofstream out("file.txt"); 也是表示打开file.txt,返回 out流指针,只不过他是隐式调用 open函数,因为ofstream类的构造函数中就有调用了open函数
同理:
ifstream in("file.txt"); 也是等价于 ifstream in; in.open("file.txt");
2.指针打开文件的权限模式:(在 ios 类中)
用法:
ofstream out;
out.open("file.txt",ios::app)//就是以追加内容的方式打开文件
而out.open("file.txt",ios::app|ios::trunc); 表示应用两种权限打开文件,当然可以更多,用 | 来增加
3.判断是否打开成功和是否已经到文件结尾:
(1)是否打开成功
ofstream out("file.txt");
if(!out.is_open)
{
cout<<“打开失败”<<endl;
}
//同理 ifstream in也是这样判断。
(2)是否到文件结尾
ifstream in("file.txt");
while(!in.eof)
{
fun(); //当文件没到达末尾,就执行fun()函数
}
(3)获得和设置流指针:
ifstream 有一个 get 指针,指向下一个将要被读取的元素
ofstream 有一个 put指针,指向下一个将要被写入的位置
tellg()和tellp()分别用于返回get指针,put指针的位置,并不需要输入参数
seekg()和seekp() 分别用于设置 get指针和 put指针的位置,一个两个参数,第一个为,位移量,第二个为 位置。
如:
seekg(0,ios::beg); //设置get指针的位置为,从文件开头开始位置0个位置 的地方
应用如下:获取一个文本文件大小:
#include<iostream>
#include<fstream>
using namespace std;
void get_size(ifstream &in)
{
long b,e;
b=in.tellg();
in.seekg(0,ios::end);
e=tellg();
long size=e-b;
cout<<"size="<<size<<endl;
}
int main()
{
ifstream in("file.txt");
get_size(in);
in.close();
return 0;
}