Jump to content

Add to start of file


tommy20

Recommended Posts

I have a file which I open through

 

$handle = fopen("details/horselistfile.txt", "a+");

fwrite($handle, "\n$horsearray\n");

fclose($handle);

 

I want to add to the start of the file by changing to

$handle = fopen("details/horselistfile.txt", "r+");

fwrite($handle, "\n$horsearray\n");

fclose($handle);

 

 

But it just pastes over the last entry that I had.

 

How do you prepend a file

Link to comment
Share on other sites

There is no built-in way to prepend something to a file. You have to open your file, read the contents into a variable or array, concat your new stuff to the front of the var/array,and then write the whole thing back to the file.  That's not really all that convenient if your file is large.  If your file is large I suggest you look into using a database instead.

 

edit:

 

I suppose if it's a large file and a db isn't an option, you can write your new info to a temp file and then read your existing file 1 line at a time, appending the info to the temp file 1 line at a time, and then rename your temp file to the existing file.

Link to comment
Share on other sites

Do you have a script that would prepend a line to a file. The file contains a few lines each on a separate line

 

See:

 

You can just do:

 

file_put_contents('details/horselistfile.txt', $horsearray . file_get_contents('details/horselistfile.txt'));

 

file_get_contents() and file_put_contents() do the same thing as fopen(), fread()/fwrite and fclose(), they just make things easier for you.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.