Search code examples
c++fstreamfile-handling

How to jump a line in a file using C++


I want to increase the second line in my file, but I can't. How can I do it?

Here is my file content

0
0

I want to increase the 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();
}

Solution

  • 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.