Section 13.4. Other File Functions


13.4. Other File Functions

There are three functions that allow you to work more intimately with the contents of a file: rewind( ), fseek( ), and fwrite( ). We already looked at fwrite( ), but the other two functions are new. The first, rewind( ), is a helpful function that moves the file pointer for a specified file handle (parameter one) back to the beginning. That is, if you call rewind($handle), the file pointer of $handle gets reset to the beginning. This allows you to reread a file or write over whatever you have already written.

The second, fseek( ), allows you to move a file handle's pointer to an arbitrary position, specified by parameter two, with parameter one being the file handle to work with. If you do not specify a third parameter, fseek( ) sets the file pointer to the start of the file, meaning that passing 23 will move to the 24th byte of the file (files start from byte 0, remember). For the third parameter, you can either pass SEEK_SET, the default, which means "from the beginning of the file," SEEK_CUR, which means "relative to the current location," or SEEK_END, which means "from the end of the file." For example:

     $handle = fopen($filename, "w+");     fwrite($handle, "Mnnkyys\n");     rewind($handle);     fseek($handle, 1);     fwrite($handle, "o");     fseek($handle, 2, SEEK_CUR);     fwrite($handle, "e");     fclose($handle); 

The first byte of a file is byte 0, and you count upward from therethe second byte is at index 1, the third at index 2, etc.


To begin with, the string "Mnnkyys" is written to $handle, but rewind( ) is then called to move the file pointer back to the beginning of the file (the letter "M"). The fseek( ) function is then called, with 1 as the second parameter, to move the file pointer to offset 1 in the file, which is currently the first of two letter "n"s. The fwrite( ) function is called again, writing an "o"this will replace the current letter "n" at that offset with an "o". Next, fseek( ) is called once more, passing in 2 and SEEK_CUR, which means "Move to the byte 2 ahead of the current byte," which happens to be the first of two letter "y"s. Then fwrite( ) is called for the last time, replacing that "y" with an "e", and finally the file is closed.



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net