Reputation: 31
If I write fopen($myfile, 'a')
, and $myfile
is a very large file, will the server have to read the entire file in order to return the pointer to the end of the file? Or does it quickly find the pointer to the end of the file and then return that?
On a related note, when I then use fwrite()
I assume it doesn't overwrite the whole file, right? It just appends stuff?
I'm basically trying to figure out whether fopen()
with the 'a'
option, and fwrite()
are O(1) or O(n), where n is the length of the prexisting file.
Upvotes: 3
Views: 1697
Reputation: 145482
(Related)
Note that you can also use file_put_contents
instead of fopen/fwrite/fclose
for appending to files - if you are that much concerned about speed:
file_put_contents($filename, $data, FILE_APPEND);
This is a bit more atomic, and does not necessitate locking.
Upvotes: 3
Reputation: 65126
The actual complexity depends on the complexity of the underlying filesystem, but PHP itself will not loop or read through the entire file, it will seek to the end and start writing from there. When opening a file in append more, it will not be erased by fwrite (you could easily try this to see how it works).
Upvotes: 4
Reputation: 92326
No, fopen
does not need to read the whole file just to jump to the end. A simple seek is all that is needed.
Upvotes: 1