头文件包括:#include <fstream>
一、写入到文本文件中:【首先需要将ofstream对象与文本文件关联起来】
语 句 :
ofstream outfile;
outfile.open();
while(!outfile)//判断文件打开是否成功
{ }
...
outfile<<...;
...
outfile.close();
原 型 :void open(const char *filename,int mode,int access)
参 数 :filename — —要打开的文件名;mode — —要打开文件的方式;access — —要打开文件的属性
打开文件的方式在类ios(是所有流式I/O类的基类)中定义,常用的值如下:(可以用“|”把以上属性连接起来,如ios::out|ios::binary)
ios::app: 以追加的方式打开文件
ios::ate: 文件打开后定位到文件尾,ios:app就包含有此属性
ios::binary: 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
ios::in: 文件以输入方式打开
ios::out: 文件以输出方式打开
ios::nocreate: 不建立文件,所以文件不存在时打开失败
ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败
ios::trunc: 如果文件存在,把文件长度设为0
打开文件的属性取值是:(可以用“或”或者“+”把以上属性连接起来)
0:普通文件,打开访问
1:只读文件
2:隐含文件
4:系统文件
现在的 ofstream类中的 open函数如果找不到文件,默认就创建与输入文件流关联的文本文件
二、读取文本文件:
语 句 :
ifstream infile;
infile.open();
while(!infile)//判断文件打开是否成功
{ }...
infile>>...;
eof()/fail();//测试输入是否成功
...
函 数 :
infile.open(filename)//输入文件流关联
infile.is_open() //判断文件打开是否成功判断,是则返回true,否返回false
infile.good() //infile>>正确,并且不是eof结束符判断
infile.eof() //文件结束判断
infile.fail() //文件结束判断和数据不匹配
infile.close(); //文件关闭
三、文件定位函数:
C++中文件读位置的定位函数:infile.seekg(streamoff offset,seek_dir origin);
C++中文件写位置的定位函数:outfile.seekp(streamoff offset,seek_dir origin);
seek_dir表示移动的基准位置:ios::beg[文件开头]ios::cur[文件当前位置]ios::end[文件结尾]
从 vs 2003 开始,微软用一个新的 iostream 替换了原来的,新包中没有 nocreate 标识符,
现在的 ifstream类中的 open函数默认打开就是不创建文件。如果没有这个文件则打开出错,而不是创建文件。
#include <iostream>
#include <fstream> //file I/O support
#include <cstdlib> //support for exit()
using namespace std;
void main()
{
const int SIZE=60;
char filename[SIZE];
ifstream infile;
cout<<"Enter name of data file:";
cin.getline(filename,SIZE);
infile.open(filename);
if(!infile.is_open())
{
cout<<"Could not open the file :"<<filename<<endl;
cout<<"Program terminating.\n";
exit(EXIT_FAILURE);
}
double value;
double sum=0.0;
int count=0;
do
{
infile>>value;
sum+=value;
count++;
}while(infile.good()); //while input good and not at EOF
if(infile.eof())
cout<<"End of file reached.\n";
else if(infile.fail())
cout<<"Input terminated by data mismatch.\n";
else
cout<<"Input terminated for unkown reason.\n";
if(count==0)
cout<<"No data processed.\n";
else
{
cout<<"Item read:"<<count<<endl;
cout<<"sum:"<<sum<<endl;
cout<<"Average:"<<sum/count<<endl;
}
infile.close();
system("pause");
}