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, '
');
    stream << city << endl;
    for (int i = 0; i < loop-1; i++){
        getline(cin, city, '
');
        stream << city << endl;
    }

    stream.close();

    stream.open("city.txt", ios::in);
    cout << "
文件内所有的城市为:" << endl;

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

    stream.close();
    return 0;
}

运行示例:

 

原文地址:https://www.cnblogs.com/bwjblogs/p/12905773.html