Page 1 of 1

While reading text file, rewind back to beginning?

Posted: Thu Feb 21, 2008 1:07 pm
by coltsith
Hi there,

I'm currently trying to read a list of values in a text file, and then at the end, go back to the very beginning and write a new list of values.

I've tried Rewind(file) but that only seems to rewind the reader back to the beginning of the current line. How do I make it rewind all the way back to the beginning of the entire file?

I need to do this because I need this operation synchronized and am using fLock(). And if I close the file and open it again to write, there could potentially be problems in between the closing of the first read, and the opening of the second:

Code: Select all

 
flock($a)
fopen($a, read)
fclose($a)
                          // < ---- Not synchronized; Someone else calling this script could potentially open the file
                          // here.
flock($a)
fopen($a, write)
fclose($a)
 
What I'd like to be able to do is:

Code: Select all

 
flock($a)
fopen($a, read+write)
// read down list
fRewindBackToBeginningOfFile($a)
// write new list
fclose($a)
 
Thanks for any help you can give!

Re: While reading text file, rewind back to beginning?

Posted: Thu Feb 21, 2008 2:45 pm
by liljester
its hard to tell you what youre doing wrong when you dont include actual code... rewind() does reset the file pointer back to 0 in the following code:

Code: Select all

$a = fopen("a.txt", "r+b");
flock($a, LOCK_EX);
 
while($line = fgets($a)) {
    print"{$line}<br />";
}
 
rewind($a);
 
fwrite($a, (microtime() . "\r\n"));
fwrite($a, (microtime() . "\r\n"));
fwrite($a, (microtime() . "\r\n"));
fwrite($a, (microtime() . "\r\n"));
 
fclose($a);

Re: While reading text file, rewind back to beginning?

Posted: Thu Feb 21, 2008 5:58 pm
by alex.barylski
fseek() is your alternative to explicitly setting the file handle offset.

Re: While reading text file, rewind back to beginning?

Posted: Fri Feb 22, 2008 1:50 pm
by coltsith
Okay, thanks guys!

Re: While reading text file, rewind back to beginning?

Posted: Fri Feb 22, 2008 4:36 pm
by RobertGonzalez
So are you reading the file first, then looking to go back to the beginning and write to the beginning of the file? Or do you just need to write to the beginning of the file?