fwrite 从头开始​​写入而不删除

发布于 2024-11-19 18:06:58 字数 168 浏览 1 评论 0原文

我正在使用 PHP 和 fwrite 代码,但我希望每个写入位置都从文件的开头开始,而不擦除其内容。我正在使用这段代码,但它正在写入文件末尾。

$fr = fopen("aaaa.txt", "a");
fwrite($fr, "text");
fclose($fr);

I am using PHP and fwrite code, but I want every write position to start from the beginning of the file without erasing it's content. I am using this code but it is writing to the end of the file.

$fr = fopen("aaaa.txt", "a");
fwrite($fr, "text");
fclose($fr);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

逐鹿 2024-11-26 18:06:58

那么您想在文件的开头写入,将所有当前内容保留在新数据之后吗?您必须首先获取其现有内容,然后在用新数据覆盖后将其附加回文件中。

$file = 'aaaa.txt';
$oldContents = file_get_contents($file);
$fr = fopen($file, 'w');
fwrite($fr, "text");
fwrite($fr, $oldContents);
fclose($fr);

如果您想避免将原始文件的内容加载到 PHP 脚本中的内存中,您可以尝试首先写入临时文件,使用循环缓冲区或系统调用将原始文件的内容附加到临时文件中,然后删除原始文件并重命名您的临时文件。

So you want to write at the beginning of a file, leaving all of its current contents after the new data? You'll have to grab its existing contents first, then append it back into the file once you've overwritten with your new data.

$file = 'aaaa.txt';
$oldContents = file_get_contents($file);
$fr = fopen($file, 'w');
fwrite($fr, "text");
fwrite($fr, $oldContents);
fclose($fr);

If you want to avoid loading the original file's contents into memory in your PHP script, you might try first writing to a temp file, using a loop buffer or system calls to append the contents of your original file to the temp file, then remove the original file and rename your temp file.

荆棘i 2024-11-26 18:06:58

来自 PHP 站点:

注意:

如果您以追加(“a”或“a+”)模式打开文件,则您的任何数据
写入文件将始终附加,无论文件是什么
位置

我建议这样的

$handle = fopen('output.txt', 'r+');

fwrite($handle, 'Really long sentence.');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);

echo fread($handle, filesize('output.txt'));

fclose($handle);

From the PHP site:

Note:

If you have opened the file in append ("a" or "a+") mode, any data you
write to the file will always be appended, regardless of the file
position

I suggest something like this (from php.net site):

$handle = fopen('output.txt', 'r+');

fwrite($handle, 'Really long sentence.');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);

echo fread($handle, filesize('output.txt'));

fclose($handle);
鹿港巷口少年归 2024-11-26 18:06:58
$file = 'aaaa.txt';
$tmp = file_get_contents($file);
$tmp = 'text'.$tmp;
$tmp = file_put_contents($file, $tmp);
echo ($tmp != false)? 'OK': '!OK';
$file = 'aaaa.txt';
$tmp = file_get_contents($file);
$tmp = 'text'.$tmp;
$tmp = file_put_contents($file, $tmp);
echo ($tmp != false)? 'OK': '!OK';
怪我入戏太深 2024-11-26 18:06:58

使用此代码:

$file = 'aaaa.txt';
$oldContents = file_get_contents($file);
$fr = fopen($file, 'w');
$newmsg="text".$oldContents;
fwrite($fr, $oldContents);
fclose($fr);

use this code :

$file = 'aaaa.txt';
$oldContents = file_get_contents($file);
$fr = fopen($file, 'w');
$newmsg="text".$oldContents;
fwrite($fr, $oldContents);
fclose($fr);
十六岁半 2024-11-26 18:06:58

使用 file_get_contents 预取旧内容并在写入新内容后附加它是一种方法。
但是,如果文件是动态写入的,并且在此过程中您需要返回到文件的开头并添加一些文本,则方法如下:

$handle = fopen($FILE_PATH, 'w+');
fwrite($handle, "I am writing to a new empty file 
                and now I need to add Hello World to the beginning");

要在前面添加 Hello World,请执行以下操作:

$oldText = '';
fseek($handle, 0);
while (!feof($handle)) {
   $oldText .= fgets($handle);
}
fseek($handle, 0);
fwrite($handle, "Hello World! ");
fwrite($handle, $oldText);

fclose($handle);

结果将是:

世界你好!我正在写入一个新的空文件
现在我需要将 Hello World 添加到开头

提醒中,就像 Fabrizio 已经指出的那样:

如果您以追加(“a”或“a+”)模式打开文件,则您的任何数据
写入文件将始终附加,无论文件是什么
位置

Prefetching old content with file_get_contents and appending it after writing new content is one way to do it.
But In case, the file is being dynamically written and along the way you needed to go back to the beginning of file and add some text, then here is how:

$handle = fopen($FILE_PATH, 'w+');
fwrite($handle, "I am writing to a new empty file 
                and now I need to add Hello World to the beginning");

to prepend Hello World do the following:

$oldText = '';
fseek($handle, 0);
while (!feof($handle)) {
   $oldText .= fgets($handle);
}
fseek($handle, 0);
fwrite($handle, "Hello World! ");
fwrite($handle, $oldText);

fclose($handle);

The result would be:

Hello World! I am writing to a new empty file
and now I need to add Hello World to the beginning

Reminder and like Fabrizio already noted:

If you have opened the file in append ("a" or "a+") mode, any data you
write to the file will always be appended, regardless of the file
position

ゃ人海孤独症 2024-11-26 18:06:58

这应该有效:

$file="name.extension";
$current = file_get_contents($file);
$user = $_POST["username"];
$pass = $_POST["password"];
file_put_contents($file,$current . "Whatever you want to add here"

这会找到当前的内容,并在每次运行代码时将其复制/粘贴回来(尝试使其尽可能简单,以防其他答案有点太复杂)

This should work:

$file="name.extension";
$current = file_get_contents($file);
$user = $_POST["username"];
$pass = $_POST["password"];
file_put_contents($file,$current . "Whatever you want to add here"

This finds the current stuff and copy/pastes it back each time the code is ran (tried to make it as simple as possible in case other answers are a little too complicated)

心欲静而疯不止 2024-11-26 18:06:58
  1. 以 w+ 模式而不是 a+ 模式打开文件。
  2. 获取要添加的文本长度 ($chunkLength)
  3. 将文件光标设置到文件开头 从文件
  4. 中读取 $chunkLength 字节
  5. 将光标返回到 $chunkLength * $i;
  6. 写入 $prepend
  7. 设置 $prepend 步骤 4 中的值
  8. 执行这些步骤,而 EOF

    $handler = fopen('1.txt', 'w+');//1
    倒回($handler);//3
    $prepend = "我想将此文本添加到此文件的开头";
    $chunkLength = strlen($prepend);//2
    $i = 0;
    做{
        $readData = fread($handler, $chunkLength);//4
        fseek($handler, $i * $chunkLength);//5
        fwrite($handler, $prepend);//6
    
        $prepend = $readData;//7
        $i++;
    } while ($readData);//8
    
    fclose($处理程序);
    
  1. Open a file in w+ mode not a+ mode.
  2. Get the length of text to add ($chunkLength)
  3. set a file cursor to the beginning of the file
  4. read $chunkLength bytes from the file
  5. return the cursor to the $chunkLength * $i;
  6. write $prepend
  7. set $prepend a value from step 4
  8. do these steps, while EOF

    $handler = fopen('1.txt', 'w+');//1
    rewind($handler);//3
    $prepend = "I would like to add this text to the beginning of this file";
    $chunkLength = strlen($prepend);//2
    $i = 0;
    do{
        $readData = fread($handler, $chunkLength);//4
        fseek($handler, $i * $chunkLength);//5
        fwrite($handler, $prepend);//6
    
        $prepend = $readData;//7
        $i++;
    }while ($readData);//8
    
    fclose($handler);
    
油焖大侠 2024-11-26 18:06:58

首先以 C+ 模式打开文件,如果文件不存在,则打开文件或创建新文件,并将指针指向文件的开头。要获取旧内容,请使用 file_get_contents 并检查文件是否存在。

$fh = fopen($file_path, 'c+'); 

if (file_exists($file_path)) {   
    $oldContents = file_get_contents($file_path);  
    fwrite($fh,"New Content" );  
    fwrite($fh, $oldContents);   
} else {   
    fwrite($fh,"New Content");   
}   

fclose($fh);

First open the file in c+ mode which opens file or create new file if doesnot exists and points the pointer at beginning of the file. To get old content use file_get_contents and check if the file exists.

$fh = fopen($file_path, 'c+'); 

if (file_exists($file_path)) {   
    $oldContents = file_get_contents($file_path);  
    fwrite($fh,"New Content" );  
    fwrite($fh, $oldContents);   
} else {   
    fwrite($fh,"New Content");   
}   

fclose($fh);
情泪▽动烟 2024-11-26 18:06:58

使用 fseek() 设置您在文件中的位置。

$fr = fopen("aaaa.txt", "r+");
fseek($fr, 0); // this line will set the position to the beginning of the file
fwrite($fr, "text");
fclose($fr);

Use fseek() to set your position in the file.

$fr = fopen("aaaa.txt", "r+");
fseek($fr, 0); // this line will set the position to the beginning of the file
fwrite($fr, "text");
fclose($fr);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文