Skip to main content

PHP File Handling: Moving the File Pointer

Body

If you have remembered in one of our lesson the writing of the file, we talked about the idea of the file pointer or its like a cursor in a word processor. So in file handling we have the ability to move the pointer around the file to write in different places within the file. And this will be our focus for this lesson.

To start in this lesson lets create a new PHP file and lets call it as “filepointer.php” and add the following code.

  1. <br />
  2. <?php<br />
  3. //specify the filename and we call it as hello.txt<br />
  4. $testfile = 'hello.txt';<br />
  5. //and inside the if statement, we pass the $testfile variable to fopen and we specify the mode as write<br />
  6. //and fopen return a handle as a value, and using handle is useful because we could close it<br />
  7. if($fh = fopen($testfile, 'w')){// we are overwriting</p>
  8. <p>//returns number of bytes or false<br />
  9. $greetings = "abc\r\ndef\r\nghi";<br />
  10. fwrite($fh, $greetings);<br />
  11. //this will return the position of our pointer or cursor and we can use it as key for moving around<br />
  12. $position = ftell($fh);<br />
  13. //used to seek new location for us, and we're going tell what position is going to go to<br />
  14. //and it moves back five position<br />
  15. fseek($fh, $position -5);</p>
  16. <p> fwrite($fh, "rst"); </p>
  17. <p> //to go back at the beginning of the file<br />
  18. rewind($fh);<br />
  19. fwrite($fh, "xyz");<br />
  20. //close the handle<br />
  21. fclose($fh);<br />
  22. }<br />
  23. ?><br />

Output:

The output does not really give us what we are expecting so BEWARE it will OVERTYPE, and the second thing is that those modes do matter a little bit because “a” and “a+” modes will not let you move the pointer. They put it at the end of the file and forces to append.

So if we want to able to append, but then we might jump back to the beginning we need to use something “r” or “r+” as one of our options so that we can go to the end of our file write something jump back to the beginning and write something else. But at least you know how to move the pointer around.

Add new comment