Strange file reading problem

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
moppit
Forum Newbie
Posts: 1
Joined: Sun Jul 18, 2004 5:12 pm

Strange file reading problem

Post by moppit »

Hey,

I'm working on a little class that handles data storage in text files, and came across a frustrating little problem. Although I've solved it now, I don't actually understand what the problem was, and would really like some clarification of it!

My issue is with the following code:

Code: Select all

fseek($this->f, -1*strlen(RS), SEEK_END);
  $tmp = fread($this->f, strlen(RS)+1);
  if ($tmp != RS) fwrite($this->f, RS);
...the aim of which is simply to identify whether \r\n (RS here) was the last thing written to the file; if not, write it before continuing.

Note the second line. When I had it as just fread($this->f, strlen(RS)), without +1, it would read the last two bytes fine, but the subsequent fwrite would not write anything! It returned no error, but just wrote 0 bytes.

Things get stranger, because when I inserted the following after the second line:

Code: Select all

fseek($this->f, 0, SEEK_CUR);
everything worked as expected! Correct me if I'm wrong, but that fseek() does nothing with the pointer.

I realised eventually that the problem might have something to do with EOF, and let fread() read an extra byte - that solved the problem!

So the question is (finally), why can't fwrite() insert data just before EOF, as I was trying to get it to do???

(BTW, just to make things scarier, an feof() after line 2 retured true when I did the +1 thing, but NOT when I did fseek() fix)

I'd appreciate any clarification on EOF and PHP's handling of it, if there's some crucial logic I'm missing here.

Thanks!
Post Reply