I’m creating a class that will store data in a file and I need to know if it’s possible to do multiple read/writes using one file handle?
I’ve done some experiments, and using this code:
$file_name = 'test.txt';
$file = fopen($file_name, 'r+');
echo fread($file, filesize($file_name)) . "<hr />";
fwrite($file, "|".rand());
echo fread($file, filesize($file_name));
fclose($file);
The file gets read the first time, the write works, but the second fread is blank.
Using this code:
$file_name = 'test.txt';
$file = fopen($file_name, 'r+');
echo fread($file, filesize($file_name)) . "<hr />";
fwrite($file, "|".rand());
fclose($file);
$file = fopen($file_name, 'r+');
echo fread($file, filesize($file_name));
fclose($file);
The second fread then works, but it doesn’t contain the data that was appended to it in the fwrite just above it.
So basically, I want to create a single file handle as a property of the class, and have it’s methods refer to it when reading and writing, but including any changes that other methods might’ve made to the data.
I do have 2 alternatives if this isn’t possible, one being opening and closing the file handle in each method but this seems really inefficient and I’m not sure what a single file open/close ‘costs’ in terms of performance. The other alternative is that the data is being converted into array for easy manipulation, I could update the array rather than the file every time but then when would I update the file?
Check out
fseekto move your pointer within the file and read from there, fread and fwrite are moving that pointer forward.And you have to use
a+instead ofr+, see: the mode offopen