By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,335 Members | 2,218 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,335 IT Pros & Developers. It's quick & easy.

Insert string to file at specific location

P: n/a
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
Nov 1 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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.
js*******@attglobal.net
==================
Nov 1 '05 #2

P: n/a
I would never rewrite the file like that if there were any danger of
data-loss.

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

Nov 1 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.