replace line in a file C++

后端 未结 4 1705
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 15:40

I\'m trying to find a way to replace a line, containing a string, in a file with a new line.

If the string is not present in the file, then append it to the file.

4条回答
  •  感动是毒
    2020-12-30 16:35

    As mentioned, the code by KarlPhilip is a good starting point (thanks), but did not work correctly according to the ">= 0". Comparing to "0" it is known for MS CString-types and in C#, etc, but it seems not to work properly with the STL. E.g. in VS 2010 (only release), the C++ code behaved wrong with this compare without throwing an error!

    Here is a correction to C++ standards: If some wizards have improvements, please post them. I think, it is a very useful and important question/snippet.

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;    
    
    int main() 
    {   
       string search_string = "cactus";   
       string replace_string = "oranges";   
       string inbuf;
       // Todo: Check, if input_file exists before. 
       // Todo: Try/catch or check, if you have write access to the output file.
       fstream input_file("demo.txt", ios::in);   
       ofstream output_file("result.txt");
    
       while (!input_file.eof())   
       {
          getline(input_file, inbuf);
          size_t foundpos = inbuf.find(search_string);
          if(foundpos != std::string::npos)
          {
             string tmpstring = inbuf.substr(0,spot);
             tmpstring += replace_string;
             tmpstring += inbuf.substr(spot+search_string.length(), inbuf.length());
             inbuf = tmpstring;
          }
    
          output_file << inbuf << endl;   
       }
    
       //TODO: delete demo.txt and rename result.txt to demo.txt      
       // to achieve the REPLACE effect. 
    }
    

    I used the following replacement part inside the "if" from another SO question (The code above only replace the first occurrence):

    if(foundpos != std::string::npos)
       replaceAll(inbuf, search_string, replace_string); 
    
    //http://stackoverflow.com/questions/3418231/c-replace-part-of-a-string-with-another-string
    //
    void replaceAll(std::string& str, const std::string& from, const std::string& to) 
    {
        size_t start_pos = 0;
        while((start_pos = str.find(from, start_pos)) != std::string::npos) 
        {
            size_t end_pos = start_pos + from.length();
            str.replace(start_pos, end_pos, to);
            start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
        }
    }
    

提交回复
热议问题