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


In reply to Re: begining of a file by Hofmator
in thread begining of a file by sOKOle

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.