C++从文件中读数据及向文件中写数据

1.从文件中读数据

#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
int main(int argc, char**argv)
{
        fstream myfile;
        myfile.open("./test.txt", ifstream::in);
        if (myfile.is_open())
        {
                //方法一:使用getline,一行一行地读
                vector<string> vStr;
                string buff;
                while (getline(myfile, buff))
                {
                        vStr.push_back(buff);
                }
    
                //注意:使用以下两种方法,遇到空格,会自动换行

                //方法二:使用流
                //string buff;
                //vector<string> vStr;
                //while (myfile >> buff)
                //{
                //      vStr.push_back(buff);
                //}

                //方法三:使用istream_iterator迭代器
                //vector<string> vStr;
                //istream_iterator<string> in(myfile), end;
                //while (in != end)
                //{
                //      vStr.push_back(*in++);
                //}
                //方法三可以简写为:
                //istream_iterator<string> in(myfile), end;
                //vector<string> vStr(in, end);

                //打印读取到的内容
                for(auto i : vStr)
                {
                        cout << i<< endl;
                }
        }
        myfile.close();

        system("pause");
}

2.向文件中写数据

#include <iostream>
#include <string>
#include <fstream> //文件流工具类头文件
using namespace std;

void test()
{
    //1,包含头文件fstream

    //2,创建文件流对象
    ofstream ofs;

    //3,打开文件流对象
    ofs.open("textWXD.txt", ios::out);

    //4,写数据 “<<”
    ofs << "peggy" << endl;

    //5,关闭文件流对像
    ofs.close();
}

int main()
{
    test();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值