Computernerd
Computernerd

Reputation: 7762

Determine position of pointer in text file

Assuming i have a text file

ID       Name         A1      B1       C1     D1
1234567  Bob Persie   12.1    33.0     44.0   55.0
7654321  Tom Hard     12.2    13.0     31.0   3.0

I need to append the word:talking to the word: Tom so it will look like this

ID       Name         A1      B1       C1     D1
1234567  Bob Persie   12.1    33.0     44.0   55.0
7654321  Tomtalking Hard     12.2    13.0     31.0   3.0

I know i need to use the readt.seekp function to set the pointer to the position after the letter 'm' in the word: Tom.

I have trouble determing the position of the letter 'm'.

readt.seekp(position, ios::beg);

Upvotes: 1

Views: 493

Answers (2)

Sebastian Mach
Sebastian Mach

Reputation: 39109

You have to rewrite the whole file, you cannot just insert some text like you are used to from a text-editor, you can only overwrite existing content and append to the end of the file.

One possible solution might be to read line by line, massage the line, write line by line into a temporary file, and finally rename the temporary file to your original's file name.

For the massage, do a string-replace. So:

source = open(sourcename, read-only)
(temp, tempname) = tempfile(write-only)

for each line in source:
    line.replace("Tom", "Tomtalking")
    temp.write(line)

close(temp)
close(source)
rename(tempname, sourcename)

Upvotes: 2

WeaselFox
WeaselFox

Reputation: 7380

read the whole file line by line - into a vector of strings for example, do the appending you need and overwrite the file. This is a more common and simple way to do it than seekp.

Upvotes: 1

Related Questions