Skip to main content

PHP File Handling: Moving the File Pointer


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

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.

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.