檔案流fstream和字串流sstream的使用
阿新 • • 發佈:2019-01-31
檔案流就是將流與檔案進行繫結,讀寫檔案。字串流就是將流與字串進行繫結,讀寫字串。
檔案流類有ifstream,ofstream和fstream,而字串流類有istrstream,ostrstream和strstream。檔案流類和字串流類都是ostream,istream和iostream類的派生類,因此對它們的操作方法是基本相同的。
以下以例項說明檔案流的使用方法:
#include "stdafx.h" #include <string> #include <iostream> #include <fstream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { /***IO標準庫使用C風格的字串而不是C++(string)風格的字串,故要呼叫c_str()函式。***/ //定義流,並繫結相應的檔案,如果檔案不存在會建立檔案 1--------- string strfilein = "1.txt",strfileout = "2.txt"; //定義讀入流並繫結檔案,作用:將檔案中的資料讀入到string等 ifstream infile(strfilein.c_str(),ifstream::in|ifstream::binary); //定義寫入流並繫結檔案,作用:將string的資料讀入到檔案等 //指定app模式,這樣開啟檔案後,檔案中原有的資料就不會被刪除 ofstream outfile(strfileout.c_str(),ofstream::out|ofstream::app); //定義流,並繫結相應的檔案,如果檔案不存在會建立檔案 2--------- string strfilein1 = "3.txt",strfileout1 = "4.txt"; ifstream infile1; //定義讀入流 ofstream outfile1; //定義寫入流 infile1.open(strfilein1.c_str());//讀入流繫結檔案,使用檔案預設的模式 outfile1.open(strfileout1.c_str());//寫入流繫結檔案,使用檔案預設的模式 //判斷檔案開啟是否成功---------------------- if(!infile) { cout<<"開啟檔案失敗:infile"<<endl; infile.close(); //關閉流並不能清空流的內部狀態 infile.clear();//清空流的內部狀態 }else{ cout<<"開啟檔案成功:infile"<<endl; } if(!outfile) { cout<<"開啟檔案失敗:outfile"<<endl; outfile.close(); //關閉流並不能清空流的內部狀態 outfile.clear();//清空流的內部狀態 }else{ cout<<"開啟檔案成功:outfile"<<endl; } if(!infile1) { cout<<"開啟檔案失敗:infile1"<<endl; infile1.close(); //關閉流並不能清空流的內部狀態 infile1.clear();//清空流的內部狀態 }else{ cout<<"開啟檔案成功:infile1"<<endl; } if(!outfile1) { cout<<"開啟檔案失敗:outfile1"<<endl; outfile1.close(); //關閉流並不能清空流的內部狀態 outfile1.clear();//清空流的內部狀態 }else{ cout<<"開啟檔案成功:outfile1"<<endl; } //將 infile 與新檔案重新繫結----------------- infile.close();//首先關閉infile infile.clear();//清空內部狀態 infile.open("5.txt");//然後繫結 //------------------------------------------------- string strcontent; while (!infile.eof()) { infile >> strcontent;//遇到 空格\t、回車\n 結束輸入 //getline(infile,strcontent);//一次讀取檔案中的一行 outfile << strcontent;//寫入到檔案裡 } return 0; }