tags:

views:

50

answers:

2

I am working on a file-handler class and am running into some issues with file streams. Providing functionality for operations such as append and overwrite are a simple matter of changing the mode passed to fopen.

However, providing an easy way to insert, update, and delete is proving to be more challenging. Pretty much, all the problems I'm having is with fwrite.

Insert - As far as I can tell, there is not a way to insert characters at a location other than the end of the file using fwrite. The two options I've come up with is using file_get_contents and heavily using fseek/fwrite to extend the file.

Delete - Unfortunately, trying to write NULL using fwrite is not the same thing as a 'deleting' a character. As with inserting data, the options again are file_get_contents and fseek/fwrite.

Update - Updating data within a file is a combination of the insert/delete problems. If the new value is shorter than the old value, then I'd have to delete the additional characters. If the new value is longer than the old value, I'd have to insert the additional characters. If they are the same length, then simply using fwrite will be fine.

Hopefully, there is something I'm not aware of which can resolve this problem cleanly. Each of the options I found use either file_get_contents (which I don't care for since the entire file must be read into memory) or heavily use fseek/fwrite to change the file's length (which seems convoluted to me).

Does anyone have an idea I haven't thought of?

Thanks!

+1  A: 

You could always use fseek() and fwrite() to shuffle the file in fixed-size 'chunks' rather than using file_get_contents(). The logic is fairly straightforward, but I suspect it would be cumbersome and slow if implemented directly in PHP rather than as a C library.

Mark Baker
Yeah, that's the fseek/fwrite option which I was referring to. I feel the same way about it.
Ogo
+1  A: 

That's it. Pretty much every language will do it the same way. The recommended way is to use a temporary file, and transfer the original file piece by piece, then atomically move the temp file over the original.

However, there are programs that do such things for you, and in a much more optimized way - primarily database engines.

Amadan