C++ 读取和写入txt文件

 读取文件的示例代码

#include <fstream>
#include <string>
void readTxt(string file)
{
    ifstream infile; 
    infile.open(file.data());   //将文件流对象与文件连接起来 
    assert(infile.is_open());   //若失败,则输出错误消息,并终止程序运行 

    string s;
    while(getline(infile,s))
    {
        cout<<s<<endl;
    }
    infile.close();             //关闭文件输入流 
}

代码很常见,很多博客都有,这里做个注释,并记录一下用法,方便以后查找使用

这段代码使用 c++输入文件流 ifstream 来实现txt文件的读取的

ifstream有两种构造方式

default (1) ifstream();
initialization (2)  
explicit ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
explicit ifstream (const string& filename, ios_base::openmode mode = ios_base::in);

第一种不绑定文件,后续用open() 绑定。
第二种绑定文件 filename ,读取模式默认参数为 ios_base::in可以省略。

使用到函数 ifstream::open

void open (const   char* filename,  ios_base::openmode mode = ios_base::in);
void open (const string& filename,  ios_base::openmode mode = ios_base::in);

用到函数 istream::getline

(1) 用户定义截止字符
istream& getline (istream&& is, string& str, char delim); //c++11 标准

(2) 截止字符默认'\n'
istream& getline (istream&& is, string& str); // c++11 标准

参考资料:

c++输入文件流ifstream用法详解_ims的博客-CSDN博客_ifstream

c++读取TXT文件内容 - 张成的博客 - 博客园

写入txt文件

ofstream outfile("res.txt");
outfile << "hello world!" << "," << "0" << endl;
outfile.close();

  • 10
    点赞
  • 83
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值