Jump to content

[SOLVED] is it possible to append at beginning of a file


abdfahim

Recommended Posts

In the sense your thinking of...no (say that since we've all been there ;))

 

Your gonna have to read your file into a variable. Set another var with the content you'd like at the beginning of your file, and concantenate them together, then rewrite the file.

 

$old_file = file_get_contents(...);

$new_stuff = '...';

 

$file = $new_stuff . "\n" . $old_file;

 

//rewrite the file

 

best we get for flat files, but that goes for most scripting languages. Even if there is some magic function in other languages, this is probably the process when you get down to the meat and potatoes.

 

beaten to it again...gotta stop being so longwinded ;)

Link to comment
Share on other sites

as long as you have enough memory, your good to go. But yes, it is possible to run into problems with large files. If it's really an issue, think about using a db for your app rather than flat files.

Link to comment
Share on other sites

If your file could grow to be bigger than the available memory, then you would need to read/write smaller blocks.

 

In a real world application, you would actually create a new temporary output file, write the new content to the beginning, then read blocks of your existing file and write it to the new file. Then after you have successfully written to the temporary output file, delete your old original file and rename the temporary output file to be the new actual file.

 

If there is a chance of multiple concurrent access, you would need to use file locking to prevent loss of data.

 

If this is something like a blog or an article site were you are doing this to put newer content at the start of a file so it is output first, you seriously need to consider using a database as it avoids all the problems of getting the data in the order you want and concurrent updates/file locking issues.

Link to comment
Share on other sites

  • 2 weeks later...
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.