I'm trying to write a code in C++ which basically stores key value pairs in a file separated by a space. The condition is that if the key is already present, it should just update the value(increment by 1) and write that updated value to the text file. And if the key is not already present, it should write the entire key value pair to the text file(For eg: some_param 12). Also if there are many parameters as the example I've stated, it should take just the values of all the parameters and increment all of those values by 1. I am able to write the initial key value pair to the text file but after that I am not able to parse the file just for taking out the value to increment by 1.
This is the code I have:
fstream fn,fn1;
key = "number_of_flights";
value = 1;
fstream tempfile;
fn.open("samplefile.txt");
if(fn){
cout << "File Exists" << endl;
fn1.open("samplefile.txt", ios::in);
if(fn1.is_open()){
cout << "File is open...." << endl;
while(getline(fn1, line)){
line = "Hello";
pos = line.find(" ");
cout << pos << endl;
str = line.substr(pos+1);
value = stoi(str);
cout << str << endl;
line[pos+1] = value+1;
fn1 << line << endl;
}
fn1.close();
}
}
else{
cout << "File doesn't exist, creating file......." << endl;
fn.open("samplefile.txt", ios::out);
if(fn.is_open()){
cout << "File created and opened, writing to File........";
fn << key << " " << value << endl;
fn.close();
}
else{
cout << "Cannot open file";
}
}
Can someone please help as I'm trying to figure this out from a really long time. Thanks in advance.