#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;
}
}