Replace a string in a text file

I want to replace a line of text in a file, but I do not know any functions.

I have it:

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

Any answers for this?

I miss to say to add text to some line in a file ...

Example

 infile.add(text, line); 

Does C ++ have functions for this?

+4
source share
3 answers

I'm afraid you might 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 want this to replace the first event. In addition, I forgot at the end to add code that removes filein.txt and renames fileout.txt to filein.txt.

+6
source

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

+3
source

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 first modification. You cannot "make space" in the middle of a file for new lines.

A reliable way to do this is to copy the contents of the file to a new file, make changes while you work, and then use rename to overwrite the old file with the new one.

+3
source

Source: https://habr.com/ru/post/1399065/


All Articles