[Tutor] how to write a line

Alan G alan.gauld at freenet.co.uk
Tue Jul 26 00:45:42 CEST 2005

> but how do i overwrite a line value with another value ?
> i mean, how do go to, say, line 3 of a text file and replace
> what is written on line 3 with something else?

You can't do it directly easily unless the new version
happens to be the exact same length as the original.

In practice you have to adopt the same approach as your 
word processor does: read the file into memory, change the 
line in memory then write the whoile file back out 
overwriting the original file (you may want to save the 
original version as a backup while your at it!)

If the change is the exact same number of bytes you can 
do it by messing around with the seek() and write() functions
but its messy and easy to get wrong!

There are some examples of the first approach in my tutorial 
in the file handling topic...

Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list