Search code examples
c++filetextio

How can I find and replace a line of data in a text file c++


I am trying to find and replace a line of data in a text file in c++. But I honestly have no idea where to start.

I was thinking of using replaceNumber.open("test.txt", ios::in | ios::out | ios_base::beg | ios::app);

To open the file at the beginning and append over it but this doesn't work.

Does anyone know of a way to achieve this task?

Thanks

Edit: My text file is only one line and it contains a number for example 504. The user then specifies a number to subtract then the result of that should replace the original number in the text file.


Solution

  • Yes, you can do this using std::fstream, here's an example implementation. You open the file, iterate over each line in the file, and replace any occurrences of your substring. After replacing the substring, store the line into a vector of strings, close the file, reopen it with std::ios::trunc, and write each line back to the empty file.

    std::fstream file("test.txt", std::ios::in);
    
    if(file.is_open()) {
        std::string replace = "bar";
        std::string replace_with = "foo";
        std::string line;
        std::vector<std::string> lines;
        
        while(std::getline(file, line)) {
            std::cout << line << std::endl;
            
            std::string::size_type pos = 0;
            
            while ((pos = line.find(replace, pos)) != std::string::npos){
                line.replace(pos, line.size(), replace_with);
                pos += replace_with.size();
            }
            
            lines.push_back(line);
        }
    
        file.close();
        file.open("test.txt", std::ios::out | std::ios::trunc);
        
        for(const auto& i : lines) {
            file << i << std::endl;
        }
    }