Replace a line in text file

67,881

Solution 1

I'm afraid you'll probably have to rewrite the entire file. Here is how you could do it:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    string strReplace = "HELLO";
    string strNew = "GOODBYE";
    ifstream filein("filein.txt"); //File to read from
    ofstream fileout("fileout.txt"); //Temporary file
    if(!filein || !fileout)
    {
        cout << "Error opening files!" << endl;
        return 1;
    }

    string strTemp;
    //bool found = false;
    while(filein >> strTemp)
    {
        if(strTemp == strReplace){
            strTemp = strNew;
            //found = true;
        }
        strTemp += "\n";
        fileout << strTemp;
        //if(found) break;
    }
    return 0;
}

Input-file:

ONE
TWO
THREE
HELLO
SEVEN

Output-file:

ONE
TWO
THREE
GOODBYE
SEVEN

Just uncomment the commented lines if you only want it to replace the first occurance. Also, I forgot, in the end add code that deletes filein.txt and renames fileout.txt to filein.txt.

Solution 2

The only way to replace text in a file, or add lines in the middle of a file, is to rewrite the entire file from the point of the first modification. You cannot "make space" in the middle of a file for new lines.

The reliable way to do this is to copy the file's contents to a new file, making the modifications as you go, and then use rename to overwrite the old file with the new one.

Solution 3

You need to seek to the correct line/char/position in the file and then over-write. There is no function to search and replace as such (that I know of).

Share:
67,881
Warkanlock
Author by

Warkanlock

Programmer Indie in Study and Game Developer "Be the world and the world be me"

Updated on July 22, 2022

Comments

  • Warkanlock
    Warkanlock almost 2 years

    I want replace a line of text in a file, but I don't know a functions to this.

    I have this:

    ofstream outfile("text.txt");
    ifstream infile("text.txt");
    
    infile >> replace whit other text;
    

    Any answers for this?

    I miss to say, for add text in Some line in the file...

    Example

    infile.add(text, line); 
    

    Does C++ have functions for this?

  • Warkanlock
    Warkanlock about 12 years
    Mmm yes, seekg and seekp infile.seekg(20*i, ios::beg); infile.read(cad, 20); No?
  • zwol
    zwol about 12 years
    This won't work if the replacement text is not exactly the same size in bytes as what it replaces.
  • ildjarn
    ildjarn over 7 years
    You can avoid a potential allocation (and save a line) by replacing strTemp += "\n"; fileout << strTemp; with fileout << strTemp << '\n';.
  • Duloren
    Duloren about 3 years
    To follow the strategy to create a modified copy and then rename it with original name it is noteworthy to copy the permissions and file attributes as well.