Editing a file in C++ : help me

Discussion in 'Programming' started by rahuldas14, Oct 28, 2009.

  1. #1
    I want to edit a text file using c++.
    Suppose the content of the file is:

    I am a boy.
    I am 20 years old.
    I live in India.

    Now I want to make it:

    I am a boy.
    I am 22 years old.
    I live in India.

    I want to change it this way. Find a particular word and replace it. Is it possible to do it this way rather than replacing the whole file by duplicating the the unchanged content.
    Please help me.
     
    rahuldas14, Oct 28, 2009 IP
  2. organicCyborg

    organicCyborg Peon

    Messages:
    330
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I found this code ages ago, and it's worked nicely for me.

    
    #include <iostream>
    #include <string>
    #include <sstream>
    
    using namespace std;
    
    int main()
    {
        string originalText = "This is a test string";
        string search = "test";
        string replace = "new";
    
        string buffer = "";
        stringstream replaced("");
        stringstream original(originalText);
    
        while (original >> buffer)
        {
            if (buffer == search) replaced << replace << " ";
            else replaced << buffer << " ";
        }
        cout << replaced.str();
    
        return 0;
    }
    
    
    Code (markup):
     
    organicCyborg, Oct 29, 2009 IP
  3. rahuldas14

    rahuldas14 Well-Known Member

    Messages:
    679
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    130
    #3
    I dont think you code edits a text file.
     
    rahuldas14, Oct 31, 2009 IP
  4. iRU

    iRU Peon

    Messages:
    412
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You do know how to read and write a text file right?
    By using above algorithm, it can be done.

    1- Read the text file
    2- Find the word (by using string) that you want to change
    3- Replace the string

    Done
     
    iRU, Nov 2, 2009 IP