頭文件:#include<fstream>
使用前需要在申明全局變量的地方寫上:
ifstream fin;
ofstream fout;
優勢:適合做游戲的存檔、讀檔操作,可以同時 通過文件讀入(fin>>a;)、輸出(fout<<a;) 通過控制台窗口讀入(cin>>a;)、輸出(cout<<a);
操作:
fin.open(文件名); 打開文件讀入,不會清空文件
fin.close(); 關閉文件讀入,一定要,否則無法打開另一個文件
fout.open(文件名); 打開文件輸出,會清空文件
fout.close(); 關閉文件輸出,一定要,否則無法打開另一個文件
ofstream(文件名); 創建文件
DeleteFile(文件名);刪除文件
如果要打開一個文件,文件名是用一個字符串或字符串加上一個字符串得到的,那么要寫成這樣:
string s="123456";
fin.open((s+".txt").c_str());
fout.open((s+".txt").c_str());
創建、刪除文件:
string s="123456";
ofstream((s+".txt").c_str());
DeleteFile((s+"txt").c_str());
也可以這樣寫:
string s="123456.txt";
fin.open(s.c_str());
fout.open(s.c_str());
ofstream(s.c_str());
DeleteFile(s.c_str());
fin>>x; 從文件中讀入x,用法與cin相同
fout<<x; 往文件中輸出x,用法與cout相同
|版權聲明:本文為博主原創文章,未經博主允許不得轉載。