“流”文件是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!