dongpao9437 2019-01-11 10:45
浏览 19


I need to upload data from multiple sources into a single file, the chunks come in whatever order and I'm having trouble actually writing them into the file.

Here's an example:

function create_file($path, $size_b) {
    $f = fopen($path, "w");
    fseek($f, $size_b - 1, SEEK_CUR);
    fwrite($f, "0");

function write_file_chunk($path, $offset, $chunk) {
    $f = fopen($path, "w");
    fseek($f, $offset, SEEK_CUR);
    fwrite($f, $chunk);

$name = "boo.txt";
create_file($name, 128);
write_file_chunk($name, 10, "hello");
write_file_chunk($name, 0, "hello");

The problem is that fwrite just writes the string to where instructed and then just ends the file there regardless of whether there was data after it or not.

Is there a way to make fwrite not touch the rest of the file so I can fill out the file in a random order?

  • 写回答

1条回答 默认 最新

  • dongzhunqiu4841 2019-01-11 11:16

    fopen mode w truncates the file to zero length.

    Use r+, as this user comment on fseek suggests,

    if you're using fseek() to write data to a file, remember to open the file in "r+" mode, example:


    DON'T open the file in mode "a" (for append), because it puts the file pointer at the end of the file and doesn't let you fseek earlier positions in the file (it didn't for me!). Also, don't open the file in mode "w" -- although this puts you at the beginning of the file -- because it wipes out all data in the file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 数据库获取信息反馈出错,直接查询了ref字段并且还使用了User文档的_id而不是自己的
  • ¥15 将安全信息用到以下对象时发生以下错误:c:dumpstack.log.tmp 另一个程序正在使用此文件,因此无法访问
  • ¥15 速度位置规划实现精确定位的问题
  • ¥15 代码问题:df = pd.read_excel('c:\User\18343\Desktop\wpsdata.xlxs')路径读不到
  • ¥15 为什么视频算法现在全是动作识别?
  • ¥15 编写一段matlab代码
  • ¥15 用Python做岩石类别鉴定软件
  • ¥15 关于调取、提交更新数据库记录的问题
  • ¥15 之前删了盘从下vs2022遇见这个问题 搞了一整天了
  • ¥15 从Freecad中宏下载的DesignSPHysics,出现如下问题是什么原因导致的(语言-python)