Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

c++ - Replace a line in text file

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 += "
";
        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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...