While reading text file, rewind back to beginning?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
coltsith
Forum Newbie
Posts: 4
Joined: Tue Feb 12, 2008 2:17 am

While reading text file, rewind back to beginning?

Post 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!
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

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

Post 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);
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

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

Post by alex.barylski »

fseek() is your alternative to explicitly setting the file handle offset.
coltsith
Forum Newbie
Posts: 4
Joined: Tue Feb 12, 2008 2:17 am

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

Post by coltsith »

Okay, thanks guys!
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

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

Post 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?
Post Reply