C++(5):fstream操作

在C/C++中经常需要对文件进行操作,C中可以采用文件I/O或者标准I/O对文件进行操作。

在C++中新增了fstream:文件流操作类

fstream对文件的操作更为便捷,这里做简单介绍

使用fstream类需要包含头文件 <fstream>

具体使用如下:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ofstream fout("Data.txt");        //打开(没有则新建)名为“data.txt”的文件
    if ( !fout )
    {
        cerr << "open failed" << endl;        //报错
        return -1;
    }
    string data[4] = {"you","are","the","best"};
    //将data中数据写入文件,每个元素后都换行
    fout << data[0] << endl << data[1] << endl << data[2] << endl << data[3];
    fout.close();        //关闭文件
    
    string a,b,c,d;        //存储从文件中读出来的数,要先在文件中写入对应这几个变量的数字
    ifstream fin("Data.txt");    //读取名为“data.txt”的文件  注意具体类型为 ifstream
    if ( !fin )
    {
        cerr << "open failed" << endl;        //报错
        return -1;
    }
    fin >> a >> b >> c >> d;        //将数据读入变量
    cout << a << " " << b << " " << c << " " << d << endl;    //将变量打印出来查看结果
    fin.close();         //关闭文件

    return 0;
}

打印结果

[xxx@xxx xx]$ 
you are the best

快去试试吧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值