C++ fstream 创建文件

背景:

想用库去创建文件,没有文件就创建,存在则往文件末尾添加内容

    //写文件
    fstream fs;
    fs.open("/home/catkin_zed/src/pcl_detection/zed2_pic/21-12-27 13:34:01/rgb/depth/new_create.txt", ios::in);
    if(!fs) std::cout << "file not exist " << std::endl;

    ofstream outfile("/home/catkin_zed/src/pcl_detection/zed2_pic/21-12-27 13:34:01/rgb/depth/new_create.txt", ios::app);
	if (outfile.is_open()){
        std::cout << "file exist " << std::endl;
        outfile << std::to_string(lidarData_.line_dis) << std::endl;
        outfile.close();
    } 


    //读文件
    fstream fs_read;
    fs_read.open("/home/catkin_zed/src/pcl_detection/zed2_pic/21-12-27 13:34:01/rgb/depth/new_create.txt", ios::in);
    if(!fs_read) std::cout << "file not exist " << std::endl;

    ifstream outfile_1("/home/catkin_zed/src/pcl_detection/zed2_pic/21-12-27 13:34:01/rgb/depth/new_create.txt");
	if (outfile_1.is_open()){
        std::cout << "file exist " << std::endl;
        std::string outString;
        while(outfile_1.peek() != EOF)  //读完最后一个数据时,eofbit还是false,只有继续往下读才会发现到了文末才是true,所以用peek()
        {
            getline(outfile_1, outString);
            std::cout << "outString:" << outString << std::endl;
        }

        outfile_1.close();
    }
    else{
        std::cout << "open file faild" << std::endl;
    } 

fstream介绍

以下转载于:https://blog.csdn.net/qq_34801341/article/details/105745850

ofstream流:
以ios::app打开(或者“ios::app|ios::out”),如果没有文件,那么生成空文件;如果有文件,那么在文件尾追加。
以ios::app|ios::in打开,不管有没有文件,都是失败。
以ios::ate打开(或者”ios::ate|ios::out”),如果没有文件,那么生成空文件;如果有文件,那么清空该文件
以ios::ate|ios::in打开,如果没有文件,那么打开失败;如果有文件,那么定位到文件尾,并可以写文件,但是不能读文件

ifstream流:
以ios::app打开(“ios::app|ios::out”),不管有没有文件,打开都是失败。
以ios::ate打开(“ios::ate|ios::out”),如果没有文件,打开失败
如果有文件,打开成功,并定位到文件尾,但是不能写文件

fstream流
默认是ios::in,所以如果没有文件,ios::app和ios::ate都是失败,
以ios::app|ios::out,如果没有文件则创建文件,如果有文件,则在文件尾追加
以ios::ate|ios::out打开,如果没有文件则创建文件,如果有,则清空文件。
以ios::ate|ios::out|ios::in打开,如果没有文件,则打开失败,有文件则定位到文件尾
可见:ios::app不能用来打开输入流,即不能和ios::in相配合
而ios::ate可以和ios::in配合,此时定位到文件尾;如果没有ios::in相配合而只是同ios::out配合,那么将清空原文件
(ios::ate|ios::in–>在原文件尾追加内容;ios::ate—>清空原文件,ios::out是默认必带的,可加上也可不加,对程序无影响)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值