文件输入和输出流
在常用的三種流中處理文件的分別是:
iftream,ofstream,fstream;
ifstream:表示可以讀取的文件流
ofstream:表示可以寫入的文件輸出流
fstream:表示可以進行讀寫操作的文件流
1、如何讀取一個文件?
? 在c++中讀取文件要使用iostream頭文件,具體實現:
(1)必須包含頭文件iostream
(2)頭文件iostream定義可一個用于處理輸入的iostraem類
(3)頭文件中iostream聲明了一個名為cin的istream變量
(4)必須指明命名空間std;
可以結合使用cin和操作符<<進行讀取文件的各種數據類型,黑可以使用cin和get()讀取一個字符。
使用cin和getline()讀取一行字符。
<span style="font-size:18px;">#include<iostream> #include<fstream> #include<string> using namespace std; void main() {char ch;fstream openfile("F:\\a.txt0", ios::out);//可以進行讀寫文件流while (openfile.eof()){cout << "fileis not open" << endl;exit(1);}while (openfile.eof())//判斷是否到了結尾{openfile.get(ch);cout << ch;}openfile.close(); }</span> #include<iostream> #include<fstream> #include<string> using namespace std; void main() {ofstream oftest;char filename[] = "E:\\a.txt";//進行寫入操作。吧數據寫到文件中oftest.open(filename, ostream::app);oftest << a();oftest.close();} int a() {return 0; }總結
- 上一篇: 标准输入输出流
- 下一篇: 如何分配和释放存储空间