第十四周閱讀程式1:檔案流
問題及程式碼:
#include <iostream> #include <fstream> using namespace std; int main() { fstream outfile,infile; //定義檔案流物件 outfile.open("data.dat",ios::out); //以輸出方式開啟檔案 data,dat outfile<<"1111111111"<<endl; //將字串存入磁碟檔案 data.dat outfile<<"aaaaaaaaaa"<<endl; outfile<<"AAAAAAAAAA"<<endl; outfile<<"**********"<<endl; outfile.close(); //關閉磁碟檔案 data.dat infile.open("data.dat",ios::in); //以輸入方式開啟檔案 data,dat char line[80]; int i=0; while(!infile.eof()) //成功開啟檔案的時候 { i++; infile.getline(line,sizeof(line)); //得到每行的資料 cout<<i<<": "<<line<<endl; } infile.close(); //關閉磁碟檔案 data.dat return 0; }
執行結果:
執行後,在程式資料夾裡生成了一個data.dat 檔案
以記事本方式開啟檔案,看到結果正是輸入結果
執行結果,看到一共輸出了五行,而在data.dat檔案裡只有四行,那是因為在data.dat檔案的最後一行有一個回車符
知識點總結:
在運用檔案流的時候,首先標頭檔案 #include<fstream>
然後定義一個物件
ios::in 以輸入方式大開檔案
ios::out 以輸出方式開啟檔案,如果已有此名字的檔案,則將其原內容刪除
infile.getline(line,sizeof(line)); 獲得每行的資料