-1

Is that possible to insert a new line in a .txt file at the beginning?

I learned that using fwrite(filename, sentence) is adding a new line at the end.

But I am wondering is there any method to add a new line at the beginning, like if my original .txt file is

AAA

When I add a new line "BBB", it looks like

BBB
AAA
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Konan
  • 37
  • 7
  • It is not possible to "prepend" data to a file because of how everything is stored on disk. You will need to write the whole file after string that you are adding. – Dimi Jan 21 '20 at 15:49
  • @Dimi not 100% true, prepend in this context is to mean how can we prepend and store to the disk - not necessarily instantly prepend the file, I think possibly needs the comment amending to make it clearer that it is possible, it's just not a one liner (or a readable one liner) – treyBake Jan 21 '20 at 16:00

1 Answers1

2

You can use file_get_contents() to get the original data first, then prepend your string to that:

$existing = file_get_contents('/path/to/file.txt');
$fp = fopen('/path/to/file.txt', 'w');    

$myString = 'hello world'. PHP_EOL;

fwrite($fp, $myString. $existing);
fclose($fp);

here we open the file with w - to fully overwrite, not append. Because of this, we need to get the file contents before the fopen(). Then we get the existing file contents and concat it to your string, and overwrite the file.

Edit: file_put_contents() - as suggested by Nigel Ren

$existing = file_get_contents('/path/to/file.txt');
$myString = 'hello world'. PHP_EOL;

file_put_contents('/path/to/file.txt', $myString. $existing);

Edit: function to create one-liner

function prepend_to_file(string $file, string $data)
{
    if (file_exists($file)) {
        try {
            file_put_contents($file, $data. file_get_contents($file));

            return true;
        } catch (Exception $e) {
            throw new Exception($file. ' couldn\'t be amended, see error: '. $e->getMessage());
        }
    } else {
        throw new Exception($file. ' wasn\'t found. Ensure it exists');
    }
}

# then use:
if (prepend_to_file('/path/to/file.txt', 'hello world')) {
    echo 'prepended!';
}
treyBake
  • 6,440
  • 6
  • 26
  • 57