fstream类是C++编译系统提供的以数据文件为对象的输入输出操作的类库,亦称文件I/O类,fstream类是标准I/O类iostream的派生类。以后查阅用。
fstream类
操作
步骤1:添加头文件 #include <fstream.h>
步骤2:定义fstream类的对象
格式:文件流类型 文件流对象名
1 2 3 4 5 6
| ifstream infile;
ofstream outfile;
fstream iofile;
|
步骤3:打开要操作的文件
格式:文件流对象名.open( 文件对象, 打开方式 );
1 2 3 4
| iofile.open( "FileName", 打开方式 );
iofile.open( "FilePath", 打开方式 );
|
1 2 3 4 5 6 7 8 9 10
| iofile.open( 文件对象, ios::in );
iofile.open( 文件对象, ios::out );
iofile.open( 文件对象, ios::in | ios::out );
iofile.open( 文件对象, ios::out | ios::app );
iofile.open( 文件对象, ios::out | ios::binary );
|
步骤4:设置文件读写指针位置
格式:文件流对象名.tellg/p(); //获得文件指针当前位置
格式:文件流对象名.seekg/p( 绝对位置值 ); //将文件指针移到指定位置
格式:文件流对象名.seekg/p( 位移量,参照位置值 ); //以参照位置为基础移动位移量
1 2 3 4 5 6 7 8
| iofile.seekg/p( 100 );
iofile.seekg/p( 50, ios::cur );
iofile.seekg/p( -50, ios::cur );
iofile.seekg/p( -50, ios::end );
|
步骤5:对文件进行读写操作
格式:文件流对象名.get/put( 字节变量 );
格式:文件流对象名.read/write( 数据地址, 数据长度 );
1 2 3 4 5 6 7 8
| iofile.get( ch );
iofile.put( ch );
iofile.read( (char*)&Rbuf, 100 );
iofile.write( (char*)&Wbuf, 100 );
|
步骤6:操作结束,关闭文件
格式:文件流对象名.close();
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| #include<iostream> #include<fstream> using namespace std; int main(int argc, char const *argv[]) { fstream ioFile; ioFile.open("./a.dat",ios::out); ioFile<<"张三"<<" "<<76<<" "<<98<<" "<<67<<endl; ioFile<<"李四"<<" "<<89<<" "<<70<<" "<<60<<endl; ioFile<<"王十"<<" "<<91<<" "<<88<<" "<<77<<endl; ioFile<<"黄二"<<" "<<62<<" "<<81<<" "<<75<<endl; ioFile<<"刘六"<<" "<<90<<" "<<78<<" "<<67<<endl; ioFile.close(); ioFile.open("./a.dat",ios::in|ios::binary); char name[10]; int chinese,math,computer; cout<<"姓名\t"<<"英语\t"<<"数学\t"<<"计算机\t"<<"总分"<<endl; ioFile>>name; while(!ioFile.eof()) { ioFile>>chinese>>math>>computer; cout<<name<<"\t"<<chinese<<"\t"<<math<<"\t"<<computer<<"\t"<<chinese+math+computer<<endl; ioFile>>name; } ioFile.close(); system("pause"); return 0; }
|
所得结果如下所示
姓名 英语 数学 计算机 总分
张三 76 98 67 241
李四 89 70 60 219
王十 91 88 77 256
黄二 62 81 75 218
刘六 90 78 67 235