文件不存在创建并写入数据

一、背景

之前遗留了一个问题,就是c++没有文件创建文件的代码,这边整理一下,下次可以直接使用

二、实现


#include <iostream>
#include <fstream>
#include <vector>

#define PATH_SEPARATOR_CHAR '/'
#define PATH_SEPARATOR_STR "/"

using namespace std;

bool checkFileExist(const string &filePath) {
    fstream fs;
    fs.open(filePath, ios::in);
    if (!fs) {
        cout << "不存在该文件" << endl;

        ofstream out(filePath);
        if (out) {
            //创建成功
            cout << "创建成功" << endl;
        } else {
            //创建失败
            cout << "创建失败" << endl;
            return false;
        }
    } else {
        cout << "文件已存在" << endl;
    }

    return true;
}

std::string GetProjectPath() {
    std::string currentFilePath(__FILE__);
    string str = currentFilePath.substr(0, currentFilePath.find_last_of('/'));
    return str;
}

std::string JoinPath(const std::string &existPath, const std::string &newPart)
{
    if (existPath.back() == PATH_SEPARATOR_CHAR || existPath.empty()) {
        return existPath + newPart;
    }
    return existPath + PATH_SEPARATOR_STR + newPart;
}

void writeRateToTxt(const vector<string> &infoVector) {
    string path = GetProjectPath();
    string fileName = "resultData.txt";
    string filePath = JoinPath(path, fileName);
    if (!checkFileExist(filePath)) {
        return;
    }
    fstream fs;
    fs.open(filePath, ios::in | ios::app);
    for (vector<string>::const_iterator it = infoVector.begin(); it != infoVector.end(); it++) {
        fs << *it << endl;
    }
    fs.close();
}

int main()
{
    vector<string> vec(2);
    vec[0] = "jim";
    vec[1] = "kevin";
    writeRateToTxt(vec);
}

上述的代码实现了写文件的过程,没有文件就创建文件并写文件。需要着重指出的是ios::app是续写。

实现效果

jim
kevin

但是这边还遗留一个问题,就是重新写的时候怎么清除文件中的内容。帖子说的方法是ios::trunc。但是实验了好像不行。

三、总结

未完待续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值