C++新建txt文件,写入、读取数据

#include <fstream>
#include <string>
#include <map>
void modifyPara()
{
    // 修改数据
    std::string nameToModify = "x";
    double newValue = 0.0;
    modifyData("test.txt", nameToModify, newValue);

    nameToModify = "y";
    newValue = 1.0;
    modifyData("test.txt", nameToModify, newValue);

    nameToModify = "z";
    newValue = 2.0;
    modifyData("test.txt", nameToModify, newValue);
}

void writeDataToFile(const std::string& filename, const std::map<std::string, float>& dataMap) {
    std::ofstream file(filename);

    if (!file.is_open()) {
        std::cerr << "Error opening file!" << std::endl;
        return;
    }

    for (const auto& pair : dataMap) {
        file << pair.first << ":" << pair.second << std::endl;
    }

    file.close();
}

std::map<std::string, float> parseFile(const std::string& filename) {
    std::map<std::string, float> dataMap;
    std::ifstream file(filename);

    if (!file.is_open()) {
        std::cerr << "Error opening file!" << std::endl;
        return dataMap;
    }

    std::string line;
    while (std::getline(file, line)) {
        size_t colonPos = line.find(':');
        if (colonPos != std::string::npos) {
            std::string name = line.substr(0, colonPos);
            float value = std::stof(line.substr(colonPos + 1));
            dataMap[name] = value;
        }
    }

    file.close();
    return dataMap;
}

float readData(const std::string& filename, const std::string& name) {
    std::map<std::string, float> dataMap = parseFile(filename);
    auto it = dataMap.find(name);
    if (it != dataMap.end()) {
        return it->second;
    } else {
        std::cerr << "Name not found!" << std::endl;
        return 0.0f; // 或者返回一个表示错误的值
    }
}
void isFileExist()
{
	const char* fname = "test.txt";
	std::fstream fs;
	fs.open(fname, std::ios::in);
 
	if (!fs)
	{ 
		//创建文件
		std::ofstream fout(fname);
		if (fout)
		{
			// 如果创建成功
			std::map<std::string, float> dataMap = {{"x", 0.0}, {"y", 0.0}, {"z", 0.0}};
            writeDataToFile("test.txt", dataMap);
			// 执行完操作后关闭文件句柄
			fout.close();
		}
	}
	else
	{
		// 如果存在,读取数据
        std::string nameToRead = "x";
        float value = readData("test.txt", nameToRead);
        double x_= value;
        nameToRead = "y";
        value = readData("test.txt", nameToRead);
        double y_= value;
        nameToRead = "z";
        value = readData("test.txt", nameToRead);
        double z_= value;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值