0

I have the following php script.

<?php

create_time_stamp('time_stamp_file.txt');

function create_time_stamp($fname)
{
    $fh = fopen($fname, 'c+');
    if (!$fh) {
        die ('Could not open date stamp file');
    }
    $time = time();
    $time_array = array(
        'epochtime' => $time,
        'date' => date('Y-m-d H:i:s', $time)
    );
    fwrite($fh, json_encode($time_array)."\r\n");
}

time_stamp_file.txt had the follwoing in it:

{"epochtime":1482524298,"date":"2016-12-23 20:18:18"}

When I ran the script, I was expdecting to see the following in it:

{"epochtime":1482524540,"date":"2016-12-23 20:22:20"}
{"epochtime":1482524298,"date":"2016-12-23 20:18:18"}   

Instead, it only had a single line:

{"epochtime":1482524540,"date":"2016-12-23 20:22:20"}

I thought that c+ means, place the pointer at the beginning of the file, do not truncate it, and open it for read/write. Any ideas?

NOTE: Yes, I can read the file into a buffer, add the data to the beginning, and write it back out to the file, but my question was about the use the c+ flag.

EastsideDev
  • 6,257
  • 9
  • 59
  • 116
  • same thing for me on 5.6, use `a+` to append – Funk Forty Niner Dec 23 '16 at 20:40
  • shall I quote the manual also? http://php.net/manual/en/function.fopen.php – Funk Forty Niner Dec 23 '16 at 20:46
  • *"I thought that c+ means, place the pointer at the beginning of the file"* - that doesn't append to a file. You should read the manual on this thoroughly. – Funk Forty Niner Dec 23 '16 at 20:52
  • 1
    [Need to write at beginning of file with PHP](http://stackoverflow.com/questions/1760525/need-to-write-at-beginning-of-file-with-php) --- [How do I prepend file to beginning?](http://stackoverflow.com/questions/3332262/how-do-i-prepend-file-to-beginning) seeing that comment below. – Funk Forty Niner Dec 23 '16 at 20:54
  • I have delete the answer as it's not relevant ( I misunderstood the question). The link @Fred-ii- provided has a good memory-efficient answer. But its time efficiency is bad with the file growing large. I advice for appending to the end of the file and read the last n lines .. – Shady Atef Dec 23 '16 at 21:16

1 Answers1

0

just write fread($fh,filesize('time_stamp_file.txt')) after you open it (read the file once), it will work as expected.