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);

Tip

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

To begin with, the string "Mnnkyys" is written ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.