Reputation: 2871
I think the title pretty much says it all. I would like to prepend a String (a single line) to an existing TXT file. The existing file could potentially be very large so I'm trying to think of the most cost-efficient way of doing this.
I know the following will work:
$str = 'My new line';
$str .= file_get_contents('file.txt');
file_put_contents('file.txt', $str);
It seems overkill to have to load a huge file to just prepend a single line.
Thoughts?
Upvotes: 2
Views: 1050
Reputation: 228
$filename = 'text.txt';
$str = 'My new line';
$tmpname = 'tmp.txt';
$context = stream_context_create();
$fp = fopen($filename, 'r', 1, $context);
file_put_contents($tmpname, $str);
file_put_contents($tmpname, $fp, FILE_APPEND);
fclose($fp);
unlink($filename);
rename($tmpname, $filename);
Upvotes: 3
Reputation: 212502
I'm inclined to use a PHP stream like php://temp
which doesn't use the same memory as PHP, so isn't subject to the same limitations
$src = fopen('dummy.txt', 'r+');
$dest = fopen('php://temp', 'w');
fwrite($dest, 'My new line' . PHP_EOL);
stream_copy_to_stream($src, $dest);
rewind($dest);
rewind($src);
stream_copy_to_stream($dest, $src);
fclose($src);
fclose($dest);
Upvotes: 5
Reputation: 228
$str = 'My new line';
file_put_contents('file.txt', $str, FILE_APPEND | LOCK_EX);
Upvotes: -1