|
Posted by Jerry Stuckle on 11/01/05 03:40
Fang wrote:
> 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;
> while($i<4){
> $theData += fgets($handle);
> $i++;
> }
> fputs($handle, $content); //write
> fclose($handle); //close 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.
jstucklex@attglobal.net
==================
Navigation:
[Reply to this message]
|