How to replace words in a text file with seekp

This is a discussion on How to replace words in a text file with seekp within the C++ Programming forums, part of the General Programming Boards category; My actual problem is much larger but figuring out how to do this example will help me. I want to ...

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    6

    How to replace words in a text file with seekp

    My actual problem is much larger but figuring out how to do this example will help me. I want to overwrite data that already exists in a text file but I can't seem to do this.

    ex.
    [file.txt]
    I have five fingers.

    My current code:
    ofstream File;
    File.open("file.txt", ios:ut);
    File.seekp(8, ios::beg);
    File << "four";
    File.close();

    I have tried different combinations of ios on the second line, but it either
    a) erases the whole file and writes "four" at the begining or end
    b) writes "four" at the very end ("I have five fingers.four")
    c) erases the whole file and writes "four" eight characters into the file

    I know I can get it to work by reading in the file and going through it word by word, then re-outputting the right words and replace then at the correct time, but the actual file is extremely large so processing the whole file is not an option.
    Assuming I know the starting byte locations of everything I want to change, byte 8 in this case, how can I get the file.txt to display this:

    I have four fingers

    Is there any way to do this and avoid using ios::binary? I've tried changing File << "four"; to File.write("four", 8); but it just writes "four" eight characters into the file and nothing else is there. Thanks

  2. #2
    Registered User
    Join Date
    Dec 2006
    Location
    Scranton, Pa
    Posts
    252
    Could mess with what's below;

    Code:
    #include <fstream>
    
    int main()
    {
      
      fstream fout("changeme.txt", ios::in |ios::out |ios::beg);
                   
          fout.seekg(7, ios::beg);
          fout<<"four"<< " ";
          fout.close();
                  
      return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Storing Words from a text file
    By matt_570 in forum C++ Programming
    Replies: 18
    Last Post: 12-10-2008, 12:35 PM
  2. Removing text between /* */ in a file
    By 0rion in forum C Programming
    Replies: 2
    Last Post: 04-05-2004, 09:54 AM
  3. random selection of words from a text file
    By archie in forum C++ Programming
    Replies: 0
    Last Post: 03-02-2002, 12:59 AM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21