C++ fstream文件讀取操作


1.在頭文件fstram中,定義了了三個類型:ifstream用來從一個給定文件中讀取數據,ofstream向一個給定文件寫入數據,fstream讀寫指定文件。

2.fstream是iostream的一個基類,所以我們也可以使用<<、>>、getline等來操作fstream

3.使用>>從文件中讀取數據,和從控制cin>>類似,這種讀取方式在遇到空格時就結束一次讀取了。

int main(int argc,char *argv[]){
    std::fstream in("test.txt",std::fstream::in);//std::fstream::in表示以只讀方式打開
    bool bl = in.is_open();//判讀test.txt文件是否存在,即是否成功打開
    cout<<bl<<endl;
    string str;
    while(in>>str){//從流中讀取數據
        cout<<str<<endl;
    }
    in.close();//在流使用完畢后關閉流
}
4.使用getline從fstream中獨取數據
 std::fstream in("test.txt",std::fstream::in);
    bool bl = in.is_open();
    cout<<bl<<endl;
    string str;
    while(std::getline( in,str)){//和上面的讀取方式寫法類似,只是每次是讀取一整行
        cout<<str<<endl;
    }
    in.close();
5.使用<<向文件中寫入數據,如果目標文件不存在會自動創建文件,如果文件存在則原文件中的內容將會被覆蓋。如果想不覆蓋源文件接着在后面寫入,將下面代碼中的std::fstream::out模式換為std::fstream::out即可。
std::fstream out("test1.txt",std::fstream::out);//std::fstream::out表示以只寫的方式打開文件
    bool bl = out.is_open();
    cout<<bl<<endl;
    for(int i= 5;i<10;i++){
        out<<i<<endl;
    }
    out.close();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM