c++ 流文件读写操作

使用fstream类处理流文件

关键词: fstream()、open()、close()

使用 ofstream() 新建一个文本文件并向其中写入文本

/*************
writing
**************/
#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

int main()
{
    ofstream myfile;
    myfile.open("test.txt",ios_base::out);//ios_base::out open

    if(myfile.is_open())//is_open() check if open succeed
    {
        cout << "File open Succeed! " << endl;
        myfile << "my first text file" << endl;
        myfile << "I am PIG three." << endl;;
        cout << "Finished writing into file,will close now" << endl;
        myfile.close();//关闭流文件,以保存修改内容
    }
    else  cout << "File open failed:: check if your file is in right" << endl;
    return 0;
}

使用open()>> 运算reading 写入的文本文件

/*************
reading test.txt
***************/
#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

int main()
{
    ifstream myfile;
    myfile.open("test.txt",ios_base::in);//只读

    if(myfile.is_open())
    {
        cout << "File open Succeed! As follow: " << endl;
        string temp;
        while(myfile.good())//good()判断文件是否读完,读完退出循环
        {
            getline(myfile, temp);//一行一行读
            cout << temp << endl;
        }

        cout << "Finished reading file,will close now" << endl;
        myfile.close();//关闭流文件,以保存修改内容
    }
    else  cout << "File open failed:: check if your file is in right" << endl;
    return 0;
}

test.txt

//my first text file
//I am PIG three.

输出

这里写图片描述


技巧

在线OJ时,常在本地调试代码,可以通过文件的形式读入测试用例,降低人工输入数据的时间复杂度。

#ifdef ONLINE_JUDGE
#else
#include <fstream>
#endif

#ifdef ONLINE_JUDGE
#else
    ifstream cin("test.txt")
#endif

(全文完)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值