Insert string to file at specific location

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I want to open a file and write some string between the the 3rd line and the
4th line. my code (as follows) can insert after the 3rd line but somehow it  
owerwrites the 4th line. So i lost its original content. As my original file has
more than 10000 lines of code, I'm looking for a handy way to do that.  Does
anyone know how I can fix it? Please help me. Thanks very much.

$content = "new content here\n"
$handle = fopen("test.wrl", "r+"); //open file
$theData = "";
$i = 1;  
$theData += fgets($handle);
fputs($handle, $content); //write
fclose($handle); //close it

Re: Insert string to file at specific location

Fang wrote:
Quoted text here. Click to load it

Files don't have "lines".  They have bytes.  Lines are only logical  
breaks, defined with \n characters.

To add to the middle of a file, you have to copy the contents of the  
file to another one, inserting your text in the appropriate place as you go.

Alternatively, read the entire file into memory (i.e. into an array or a  
string), insert your data at the appropriate place and rewrite the file.

The latter sounds easier, but has two problems: if the file gets large,  
you'll need lots of memory and perhaps run out of memory.  The second is  
worse - if you have a problem when rewriting the file (i.e. server  
crashes, script times, out, etc.), you may lose the entire file.

Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.

Re: Insert string to file at specific location

I would never rewrite the file like that if there were any danger of

read in 'file.txt'
change in memory
write out 'file.tmp'
delete 'file.txt'
rename 'file.tmp' as 'file.txt'

Site Timeline