Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
- Insert string to file at specific location
November 1, 2005, 1:24 am
rate this thread
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
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
JDS Computer Training Corp.