“流”文件是C++提供的一种特殊形式的文件,也称缓冲区型文件。与普通意义文件不同,它是C++语言提
供给程序员和被除访问设备之间的一层抽象的内容,是与物理设备无关的逻辑设备。在“流”文件上,用
来写操作的函数既可用于写磁盘文件,也可用来打印机的输出,而非“流”文件与具体设备相关。C++中
有两种性质的“流”文件,即文本“流”文件(text stream)和二进制“流”文件(binar, stream)。
“流”文件通过名为FILE类型的结构来管理对文件的各种操作,定义在<stdio.h>头文件中:
typedef struct{
short level; //缓冲区满/空程度
unsigned flags; //文件状态标志
char fd; //文件描述符
unsigned char hold; //如无缓冲区不能读
short bsize //缓冲区大小
unsigned char *buffer;//数据传送缓冲区
unsigned char *curp; //当前活动指针
unsigned istemp;//临时文件指示器
short token;//FILE结构类型名
}FILE;
对于每个要处理的“流”文件,都必须为其建立一个FILE结构的信息区,可以把FILE理解为一个包含了管理“流”文件输入输出的结构类型。
“流”文件的使用:
1.创建/打开文件//创建一个FILE结构数据区,并返回该数据区的首地址。
2.文件定位
3.读/写操作
4.错误检测
5.关闭文件//对所操作的“流”文件,包括:将缓冲区中的数据写入设备文件,以及撤消该FILE数据区
例子:
#include<iostream.h>
#include<stdio.h>
#include<string.h>
#include<process.h>
void error()
{
cout<<"/nCan not open the file."<<endl;
exit(1);//Exiting program.
}
main(){
FILE *fp;//declare the variable
char str[80];
cout << " Input a string:";//input a string from the keyboard
cin.getline(str,80);
if((fp=fopen("test.dat","w"))==NULL)
error();
fputs(str,fp);//write the str to fp;
fputs("/n",fp);
fclose(fp);//Close the file;
if((fp=fopen("test.dat","r"))==NULL)
error();
char ch;
while((ch=fgetc(fp))!=EOF)
cout << ch;
cout << endl;
fclose(fp);
}
//运行结果
//Input a string:This is my first C++ stream file program!
//输出:
//This is my first C++ stream file program!