douchao1957 2016-11-15 00:27
浏览 49
已采纳

直接从文件中删除字符串而不替换PHP中的实体文件

Im trying to remove string from file by seeking its position then remove. I dont want to store the entity file in a string than replace. I need to replace it directy on the file, is there any way I could do this?

I have to find the "#" then remove until I find the next.

Example: Remove #2 data from myfile.txt

  #1|info1|info2|info3|#2|inf11|info12|inf22|#3|inf11|info12|inf22|

After remove:

  #1|info1|info2|info3|#3|inf11|info12|inf22

How can I do this?

  • 写回答

1条回答 默认 最新

  • doudieheng5322 2016-11-15 01:04
    关注

    PHP doesn't provide any way to directly manipulate file contents. You have to read into a PHP variable, then write back out to the file.

    In C on a POSIX system you can do it using mmap().

    int fd = open("myfile.txt", O_RDWR);
    struct stat stat_buf;
    fstat(fd, &stat_buf);
    size_t len = stat_buf.st_size;
    char *contents = mmap(NULL, len, PROT_WRITE, MAP_SHARED, fd, 0);
    char *num2 = strstr(contents, "#2"); // Find #2
    char *num3 = strstr(num2, "#3"); // Find #3 after #2
    memmove(num3, num2, len-(num3-contents)); // Shift everything from #3 over
    memset(contents + len - (num3 - num2), num3 - num2); // Zero the end of the file
    close(fd);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)