1

I have a few very large text files that weigh over 1GB and I constantly need to add a line to the top / beginning of the file with PHP.

I know how to do this but what is the most efficient way in doing this in terms of memory usage?

2
  • invert the problem and add the line to the end..? Commented Jan 4, 2011 at 1:18
  • That's a tough problem, see Need to write at beginning of file with PHP Commented Jan 4, 2011 at 1:19

2 Answers 2

2

You can only add to a file efficiently at the bottom. If you need to add to the top you have no other option but to rewrite the entire file.

The way to do this without reading the entire file into a buffer is to move data back in chunks until you have free space at the top.

Sign up to request clarification or add additional context in comments.

Comments

1

A different approach (if you are using a *nix platform) would be to use have PHP make system calls to cat and file redirection which would be far more efficient in terms of memory usage and performance than trying to manipulate the file header w/ PHP.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.