【问题标题】:How to change the first 512 bytes of a file?如何更改文件的前 512 个字节?
【发布时间】:2013-03-18 09:50:10
【问题描述】:

我在 PHP 中有一个大文件,我想用其他 512 个字节替换其中的前 512 个字节。是否有任何 PHP 函数可以帮助我解决这个问题?

【问题讨论】:

    标签: php file file-io stream


    【解决方案1】:

    如果您想选择性地创建文件并对其进行读写(不截断),则需要在'c+' 模式下使用fopen() 函数打开文件:

    $handle = fopen($filename, 'c+');
    

    PHP 然后具有stream_get_contents() 函数,它允许将具有特定长度(以及从文件中的特定偏移量)的字节块读取到字符串变量中:

    $buffer = stream_get_contents($handle, $length = 512, $offset = 0);
    

    但是,没有stream_put_contents() 函数可以将字符串缓冲区写回到特定位置/偏移的流中。一个相关的函数是file_put_contents(),但它不允许在特定偏移处写入文件句柄资源。但是有fseek()fwrite() 可以做到这一点:

    $bytes_written = false;
    if (0 === fseek($handle, $offset)) {
        $bytes_written = fwrite($handle, $buffer, $length);
    }
    

    这是全图:

    $handle = fopen($filename, 'c+');
    $buffer = stream_get_contents($handle, $length = 512, $offset = 0);
    
    // ... change $buffer ...
    
    $bytes_written = false;
    if (0 === fseek($handle, $offset)) {
        $bytes_written = fwrite($handle, $buffer, $length);
    }
    fclose($handle);
    

    如果$buffer 的长度不固定,这将无法正常工作。在这种情况下,最好使用两个文件并使用stream_copy_to_stream(),如How to update csv column names with database table header 中所述,或者如果文件不大,也可以在内存中执行此操作:

    $buffer = file_get_contents($filename);
    
    // ... change $buffer ...
    
    file_put_contents($filename, $buffer);
    

    【讨论】:

      猜你喜欢
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-29
      • 2012-07-21
      • 1970-01-01
      相关资源
      最近更新 更多