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 == NULL)
    {
        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 == NULL)
    {
        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

快去试试吧

猜你喜欢

转载自blog.csdn.net/Leo_csdn_/article/details/81706996