douyaosi3164 2011-09-30 13:57
浏览 27

使用php替换.txt文件的单行

I am trying to use a php call through AJAX to replace a single line of a .txt file, in which I store user-specific information. The problem is that if I use fwrite once getting to the correct line, it leaves any previous information which is longer than the replacement information untouched at the end. Is there an easy way to clear a single line in a .txt file with php that I can call first? Example of what is happening - let's say I'm storing favorite composer, and a user has "Beethoven" in their .txt file, and want's to change it to "Mozart", when I used fwrite over "Beethoven" with "Mozart", I am getting "Mozartven" as the new line. I am using "r+" in the fopen call, as I only want to replace a single line at a time.

  • 写回答

2条回答 默认 最新

  • dongsu7049 2011-09-30 14:02
    关注

    This is a code I've wrote some time ago to delete line from the file, it have to be modified. Also, it will work correctly if the new line is shorter than the old one, for longer lines heavy modification will be required.

    The key is the second while loop, in which all contents of the file after the change is being rewritten in the correct position in the file.

    <?php
    $size = filesize('test.txt');
    $file = fopen('test.txt', 'r+');
    $lineToDelete = 3;
    $counter = 1;
    
    while ($counter < $lineToDelete) {
       fgets($file); // skip
       $counter++;
    
    }
    
    $position = ftell($file);
    $lineToRemove = fgets($file);
    $bufferSize = strlen($lineToRemove);
    while ($newLine = fread($file, $bufferSize)) {
       fseek($file, $position, SEEK_SET);
       fwrite($file, $newLine);
       $position = ftell($file);
       fseek($file, $bufferSize, SEEK_CUR);
    
    }
    ftruncate($file, $size - $bufferSize);
    echo 'Done';
    fclose($file);
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值