Jump to content

fwrite() question


bachx

Recommended Posts

You have to open the file usnig append, I think. I wrote this a while ago it uses fseek to move around the pointer.

function insertInFile($file, $string, $loc)
{
$wfile = fopen($file, "r+");
if (!$wfile)
	return false;
rewind($wfile);
fseek($wfile, $loc, SEEK_SET);
$endstring = fread($wfile, (filesize($file)-$loc));
fseek($wfile, $loc, SEEK_SET);
fwrite($wfile, $string . $endstring);
fclose($wfile);
}

You will have to modify it to replace existing text.

Link to comment
Share on other sites

This is how I have updated a text file which replaces the whole file with what you enter

 

<?
$fund = file_get_contents($myFile);
$myFile = "../includes/thermometer/testFile.txt";
$name = $_POST['fund']; // vars from form
if (!isset($_POST['fund'])) {

?>	
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
    <p style="margin-left:10px;">The current fund is:<br>
    <input type="text" title="Please enter the new current fund amount" name="fund" size="30" value="<? echo $fund ?>">
</form>
<?}

else {
    $fund=$_REQUEST['fund'];
?>

<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
    <p style="margin-left:10px;">The current fund is:<br />
    <input type="text" title="Please enter the new current fund amount" name="fund" size="30" value="<? echo $fund; ?>">
</form>

<?
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = $name;
    fwrite($fh, $stringData);
    fclose($fh);
}
?>

Link to comment
Share on other sites

Like I said, you will have to modify my function to make it replace text instead of insert it. In order to replace the text, all you need to know is that length of the text you are replacing, then start the "$endstring" that many characters farther. Or a very simple method, as otuatail suggested, is to just read the entire file into a buffer, modify it, and overwrite the entire file with it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.