【C/C++】文件流操作

官网手册

c++文件流操作
http://www.cplusplus.com/reference/fstream/fstream/

一个简单的代码

#include <fstream>  

using namespace std;

int main () {

  fstream fs;
  fs.open ("test.txt", fstream::in | fstream::out | fstream::app);

  fs << " more lorem ipsum";

  fs.close();

  return 0;
}

打开方式

成员变量全称说明
ininput
outoutput
binarybinary二进制文件操作
ateat end返回文件尾端的位置
appappend从文件末尾追加内容
trunctruncate销毁源文件,然后新建打开

以上操作,可以通过运算符(|),来结合使用

in

如果文件创建过,则成功打开;否则,找不到文件
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    fstream file;
    file.open("2.txt", fstream::in);

    if (file.is_open())
    {
        cout << "打开文件" << endl;
        file.write("hellow", 6); // 无法写入文件
    }
    else
        cout << "没有创建文件" << endl;

    file.close();

    cin.get();

    return 0;
}

out

如果文件不存在,先创建,再写入;如果文件存在,直接覆盖原来内容
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    fstream file;
    file.open("1.txt", fstream::out);

    if (file.is_open())
    {
        cout << "创建并打开文件" << endl;
        file.write("hellow", 6);
    }
    else
        cout << "out 模式不能创建文件" << endl;

    file.close();

    cin.get();

    return 0;
}

(未完待续……)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值