在C++中,引入了流的概念。C++中流是指信息從輸入設備到輸出設備的過程。在C++中有三種流,標準IO流、文件IO流、字符串IO流。
在C++中派生出4個類,分別是輸入流istream、輸出流ostream、文件流基類fstreambase、字符串流基類strstreambase。在C++中如果需要對文件進行處理,必須包含#include<fstream>
頭文件。
類 | 描述信息 |
---|---|
ifstream | 表述輸入文件流,用于從文件中讀取數據 |
ofstream | 表述輸出文件流,用于創建文件并向文件中寫入數據 |
fstream | 表述文件流,具有寫數據與讀數據的兩種功能 |
void open(const char* filename,openmode mode)
文件打開模式 | 描述 |
---|---|
app | 追加 |
ate | 打開文件指定文件末尾 |
in | 輸出,打開文件用于讀數據 |
out | 輸入,打開文件用于些數據 |
linux打開文件的命令,如果我們打開文件需要兩種或者兩種以上的方式,可以使用下面這種方式。
ofstream outfile;
outfile.open("text.txt",ios::out | ios::app); //以打開、追加的模式進行打開
在打開文件后,我們需要判斷文件是否順利被打開只需要調用is_open
函數即可。
void close()
在C語言中我們使用write函數進行文件的寫入,但是在C++中增加了文件流,因此我們操作文件就非常簡單,我們可以使用流運算符進行操作。
UNIX/LINUX,讀取流運算符,用于讀取文件中的數據。
#include<iostream>
#include<fstream>
#include<string>using namespace std;int main()
{ofstream outfile;outfile.open("text.txt");if(outfile.is_open()){cout<<"outfile open file success"<<endl;string str;cout<<"please enter the content: ";cin>>str;outfile<<str;cout<<"write content success"<<endl;outfile.close();}else{cout<<"outfile open file error"<<endl;return -1;}ifstream infile;infile.open("text.txt");if(infile.is_open()){infile>>str;cout<<"Read content: ";cout<<str<<endl;infile.close();}else{cout<<"infile open file error"<<endl;return -1;}return 0;
}
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态