You are here: Re: Insert string to file at specific location « PHP Programming Language « IT news, forums, messages
Re: Insert string to file at specific location

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]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация