I wanted to insert a string of new content into an existing text file and I was having a hard time at it, but I figured it out, this is how I did it.
Instead of fooling around moving the pointer around I read the existing file in two parts.
- First part
- Second Part
- First Part
- New Information
- Second Part
$file1 = "example.txt"; // example.txt = file1
$fh = fopen($file1, "r"); //open file1 using read
$fcontent1 = fread($fh, 10); //read the first 10 lines of file1
$fcontent = fread($fh, filesize($file1)); //read the rest of file1 save as fcontent
$newcontent = " new content"; //write new content
$towrite = "$fcontent1 $newcontent $fcontent"; //now save the first part the first 10 characters in fcontent1, then your new content, then since below our pointer will have moved, you can write what is the rest of the origional file was.
fclose($fh); //close the file
$fh2 = fopen('example.txt', 'w+'); //open it up again using write+
fwrite($fh2, $towrite); //and write the new file
fclose($fh2); //close the file
0 comments:
Post a Comment