I want to increase second line in my file but I can't, please help me.
Here is my file content
0
0
I want to increase second 0 by 1, here is my code
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::fstream file;
file.open("file1.txt");
std::string line;
getline(file, line);
getline(file, line);
int a = std::stoi(line);
a;
line = std::to_string(a);
file.close();
file.open("file1.txt");
std::string line1;
getline(file,line1);
getline(file,line1);
file << line;
file.close();
}
CodePudding user response:
You are trying too hard. This is the easy way
int main()
{
std::ifstream file_in("file1.txt");
int a, b;
file_in >> a >> b;
file_in.close();
b;
std::ofstream file_out("file1.txt");
file_out << a << '\n' << b << '\n';
file_out.close();
}
Read the whole contents of the file. Make the modification needed. Write the whole contents of the file.
Doing partial updates (as you are trying) can be done, but it's tricky.