2.3.7 文件类型(1)
在编写程序时,有时需要存取文件。C++(www.cppentry.com)语言中,在进行文件操作之前需要先引入头文件fstream.h,然后声明和定义读写文件的数据流,数据流可以随意命名,但是要符合C++(www.cppentry.com)的命名规则。
如果要打开文件进行读操作,首先要创建一个ifstream对象,通过ifstream对象和磁盘上特定的文件相关联。声明ifstream对象如下。
- ifstream infile;
如果要向文件中写入数据,首先要创建一个ofstream对象,通过ofstream对象和磁盘上特定的文件相关联。声明ofstream对象如下。- ofstream outfile;
在读写文件之前,需要先把文件打开,文件操作完毕后,最好将文件关闭,因为关闭不再读写的文件可以节省系统的资源,提高执行效率。打开、关闭文件的语句如下。- 01 infile.open("文件名");
- 02 infile.close();
为了方便文件的读写操作,文件数据流fstream还提供了一些读写文件的成员函数。fstream的成员函数如表2.5所示。
表2.5 fstream成员函数表
注意:表中参数c,str为char类型,参数n为int类型。
【例2.6】 使用ifstream和ofstream对象读写文件的功能,程序代码如下。(实例位置:光盘\mr\example\第2章\2.6)
代码位置:光盘\mr\example\第2章\2.6\file\file.cpp
- 01 #include "iostream.h"
- 02 #include "fstream.h"
- 03 #include "iomanip"
- 04 int main()
- 05 {
- 06 ifstream infile;
- 07 ofstream outfile;
- 08 char name[20];
- 09 char str[30];
- 10 cout<<"请输入文件:"<<"\n";
- 11 cin>>name;
- 12 outfile.open(name);
- 13 if(!outfile)
- 14 {
- 15 cout<<"写文件打开失败!";
- 16 exit(1);
- 17 }
- 18 cout<<"请输入要写入文件的数据:"<<"\n";
- 19 cin>>str;
- 20 outfile<<str;
- 21 outfile.close();
- 22 infile.open(name);
- 23 if(!infile)
- 24 {
- 25 cout<<"读文件打开失败!";
- 26 exit(1);
- 27 }
- 28 char c;
- 29 cout<<"输出文件中数据:"<<"\n";
- 30 while(infile.get(c))
- 31 {
- 32 cout<<c;
- 33 }
- 34 cout<<"\n";
- 35 infile.close();
- 36 }