php - Overwriting Text in a File When It's Already Open -
i have file i'm opening writing, this:
if (!$idhandle = fopen($filename, 'w')) { echo "cannot open file ($filename)"; die(); }
i enter loop i'm incrementing variable, $beerid
, during each iteration. want save variable file have open, use following code:
if (fwrite($idhandle, $beerid) === false) { echo "cannot write file ($filename)"; die(); } $beerid++;
however, ends creating massive string of every beerid encounter. want have file populated last id left off on.
i realize put write outside of loop, script volatile , terminate prematurely error, want have reference last $beerid variable in event of error terminates script before loop terminated.
you must go beginning of file because fwrite
keeps track of in file. use fseek. opening , closing file several times in loop expensive , don't see reason in case. should of course close file when you're done it.
you should add before write file:
fseek($idhandle, 0);
that move beginning of file, since incrementing values won't have worry removing previous value.
edit in answer above assume id's encountered incremented values, don't so, if example encounter id=10
, , encounter id=1
above still result in 10
in file, handle add padding string you're writing using str_pad:
str_pad($value_to_write, 10); //or whatever value reasonable.
Comments
Post a Comment