skip to Main Content

As far as I am understanding c/c+ mode, I am expecting behaviour like ‘a/a+ mode, so the file shouldn’t be truncated, and any fwrite() result should be prepended to existing file.

In fact the file seems to be truncated anyway as the file always contains only tle last fwrite() content anyway.

Is it a possible bug in my PHP version (7.0), or I am misunderstanding something?

<?php
$fp = fopen($fpath,'c+');
fwrite($fp, date("H:i:s")." testn");
fclose($fp);

2

Answers


  1. What makes you think that this should behave different? According to the documentation, using c the pointer is “positioned on the beginning of the file”. Starting to write from that specific position, you would always override whatever is already present in that file

    Login or Signup to reply.
  2. Maybe a small addition to what has been said:

    <?php 
    /* file test.txt contains string(4): 'test' */
    $fp = fopen('test.txt','c+');
    fclose($fp);
    

    file test.txt is NOT truncated to zero length(as w or w+ would do on fopen() ),
    it still contains string(4): test

    Now see what happens when we write one character to the file using c+

    $fp = fopen('test.txt','c+');
    fwrite($fp, 'b');
    fclose($fp);
    

    file test.txt now contains: best, the file pointer was positioned at the beginning of the file and only overwrites the first character in the original – test has become best

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search