What are the potential pitfalls of using fseek() in PHP to write text to a specific position in a file?

Using fseek() to write text to a specific position in a file can be risky as it may overwrite existing data or leave gaps in the file. To avoid this issue, it's recommended to open the file in "r+" mode, seek to the desired position, write the new data, and then truncate the file to remove any extra content.

$file = fopen("example.txt", "r+");
if ($file) {
    fseek($file, 50); // seek to position 50
    fwrite($file, "New text to be written");
    ftruncate($file, ftell($file)); // truncate the file to remove extra content
    fclose($file);
} else {
    echo "Error opening the file.";
}