C++ fstream和文件打開模式


我們之前使用的ifstream可以創建一個輸入程序的對象,ofstream可以創建一個輸出程序的對象。而fstream可以創建既能輸入又能輸出的文件對象。也就是說,如果我們有一個對象既要進行輸入,又要進行輸出,那么fstream對象是很方便的。

fstream對象在創建時必須指定文件模式。詳細的文件模式如下:

模式 描述
ios::in 輸入
ios::out 輸出(覆蓋源文件)
ios::app 所有數據追加在末尾(在源文件末尾追加內容)
ios::ate 打開一個輸出文件並移動到文件末尾。數據可以寫入文件的任何位置
ios::trunc 如果文件已存在,則丟棄文件內容(ios::out的缺省方式)
ios::binary 以二進制格式輸入輸出(用於圖片,視頻,可執行文件等)

使用符號“|”可以組合多個模式,比如:

stream.open("city.txt", ios::out | ios::app);
//創建文件city.txt的fstream對象
//模式為追加輸出

下面舉個例子:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream stream;
    stream.open("city.txt", ios::out);

    stream << "Beijing" << endl << "Shanghai" << endl << "Guangdong" << endl << "Shenzhen" << endl;

    stream.close();

    stream.open("city.txt", ios::out | ios::app);

    int loop;
    cout << "城市的個數:" << endl;
    cin >> loop;

    string city;
    cout << "請輸入城市名(以換行區分):" << endl;
    cin.get();
    getline(cin, city, '\n');
    stream << city << endl;
    for (int i = 0; i < loop-1; i++){
        getline(cin, city, '\n');
        stream << city << endl;
    }

    stream.close();

    stream.open("city.txt", ios::in);
    cout << "\n文件內所有的城市為:" << endl;

    while(!stream.eof()){
        stream >> city;
        cout << city << " ";
    }
    cout << endl;

    stream.close();
    return 0;
}

運行示例:

 

 

 


免責聲明!

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



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