fwrite without overwriting

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mmj
Forum Contributor
Posts: 118
Joined: Fri Oct 31, 2008 4:00 pm

fwrite without overwriting

Post by mmj »

How can I add text before the end and after the beginning of a file without overwriting data?

Seems like my only option is to split the file up then put it back together later on. :banghead:
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: fwrite without overwriting

Post by Mark Baker »

Code: Select all

 
$initialData = file_get_contents('myFile.txt');
$newData = "New First Line\n".$initialData."New Last Line\n";
file_put_contents('myFile.txt',$newData);
 
mmj
Forum Contributor
Posts: 118
Joined: Fri Oct 31, 2008 4:00 pm

Re: fwrite without overwriting

Post by mmj »

Mark Baker wrote:

Code: Select all

 
$initialData = file_get_contents('myFile.txt');
$newData = "New First Line\n".$initialData."New Last Line\n";
file_put_contents('myFile.txt',$newData);
 
I mean the other way around. =)
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: fwrite without overwriting

Post by John Cartwright »

So you want to overrite the contents of the file? Simply use file_get_contents() without ammending the current files content.
mmj
Forum Contributor
Posts: 118
Joined: Fri Oct 31, 2008 4:00 pm

Re: fwrite without overwriting

Post by mmj »

Okay, if data.txt has "12567" in it then I do this:

Code: Select all

<?php
$fp = fopen('data.txt', 'r+');
fseek($fp, 2);
fwrite($fp, '34');
fclose($fp);
?>
I want "1234567" not "12347".

Basically I don't want to overwrite the data which the cursor is currently located at.

Note: this example isn't similar to what I'm doing, I'm actually modifying relatively large binary files.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: fwrite without overwriting

Post by John Cartwright »

Post some examples of what you are actually doing. Your examples involve string manipulation, however you have mentioned you are modify binary contents (which is completely different).
mmj
Forum Contributor
Posts: 118
Joined: Fri Oct 31, 2008 4:00 pm

Re: fwrite without overwriting

Post by mmj »

:banghead: :madblow:

Is there some sort of communication barrier at work here? 8O

mea culpa, I guess I should have been more descriptive in my first post.

Basically I just want to confirm what is said in this thread:

http://www.usenet-forums.com/php-langua ... iting.html

There isn't any ready-made solution to make fwrite not to overwrite.
Post Reply