檔案開啟關閉與讀寫等基本操作 C++
阿新 • • 發佈:2019-01-23
首先在c++中想要操作檔案流,必須定義標頭檔案<fstream>
而且檔案流不像標準I/O物件,所以在使用之前必須呼叫相對應的建構函式來構造建流物件。
第一可以直接呼叫建構函式
ifstream ifs// 定義檔案輸入物件
ofstream ofs //定義檔案輸出物件
fstream fs //定義檔案輸入輸出物件
第二也可以構造時指定檔名
ifstream ifs("filename"); //指定檔名
ofstream ofs("filename");
fstream fs("filename");
其次開始開啟與關閉檔案 (開啟與關閉的方式有多種,在這隻舉一種做例子)
#include<iostream> #include<cstdio> #include<fstream> using namespace std; int main() { ifstream ifs; ifs.open("C:\\Users\\lenovo\\Desktop\\1.txt",ios::in);//路徑中的'\'在open()語句中需要變成'\\' //ios::in 這是一種檔案開啟方式, if(!ifs){ cout<<"no"<<endl; }else{ cout<<"yes"<<endl; } ifs.close();//用於關閉檔案,若不關閉會消耗系統資源 return 0; }
開啟檔案之後還要進行讀寫操作
首先是讀操作
#include<iostream> #include<cstdio> #include<fstream> using namespace std; int main() { char buf[256]; ifstream ifs("C:\\Users\\lenovo\\Desktop\\1.txt");//在建構函式時指定檔名; cout<<"1.txt 內容如下:"<<endl; while(!ifs.eof()) //判斷檔案是否達到結尾 { ifs.getline(buf,256,'\n');//呼叫getline()成員函式成行輸入 cout<<buf<<endl; } if(!ifs){ cout<<"no"<<endl; }else{ cout<<"yes"<<endl; } ifs.close();//用於關閉檔案,若不關閉會消耗系統資源 return 0; }
執行結果如上,
下邊嘗試在程式中向檔案寫入字元
#include<iostream> #include<cstdio> #include<fstream> using namespace std; int main() { char buf[256]; ofstream ofs; ofs.open("C:\\Users\\lenovo\\Desktop\\1.txt",ios::out); char ch='a'; if(ofs){//判斷是否正確開啟 for(int i=0;i<26;i++) { if(i%5==0) ofs<<endl; ofs<<ch;//將字元輸入到檔案中; ch++; } } ofs.close(); ifstream ifs("C:\\Users\\lenovo\\Desktop\\1.txt"); cout<<"1.txt 內容如下:"<<endl; while(!ifs.eof()) { ifs.getline(buf,256,'\n'); cout<<buf<<endl; } ifs.close();//用於關閉檔案,若不關閉會消耗系統資源 return 0; }
執行結果如上;