in reply to begining of a file

You can't write to the beginning of a file. This is a problem which comes due to the nature of (most) file systems. Think of a file as a pile of books, it's very easy to put books on top (at the end) of it but it's not possible to put books under (at the start of) it (at least if it's very high :)

So you have to work around that problem, there are two ways to do it

  1. Open the file for read/write (as in your 2nd example). Read in the whole file. Then seek to 0. Print your first line(s) to it. Then print the rest of the file back.
  2. The problem of this is that it's not good to read in the whole file into memory (especially if it's big). So create a temporary file. Write your first lines into it, read your original file into memory but only a reasonable amount at a time (e.g. a line, 1K, 32K, ...) and write that at once out to the temp file. At the end you have to copy the temp file onto the original one (and maybe leave a backup of it somewhere).

-- Hofmator