in reply to writing to the top of a file

Make friends with seek and tell, and use a linked list. Here's how:
  1. Your file will be composed of variable-length records.
  2. Each record will be appended to the end of the file, as nature intended.
  3. The first n bytes of each record will contain the packed address of the previously-written record.
  4. The first n bytes of the first record (i.e. the first n bytes of the file) will contain the address of the last-written record.
When writing a record,
  1. Read the address of the last record from the beginning of the file. Call it $last.
  2. seek to the end of the file.
  3. Use tell to see where you are. Call this address $next.
  4. Write $last to the end of the file, then your data record.
  5. seek to the beginning of the file, and write $next there.
When reading the file,
  1. Read $last from the beginning of the file.
  2. seek to the end of the file, and use tell to get the current address. Call it $next.
  3. seek to $last, and read n bytes into the variable $prev.
  4. Read $next - $last - n bytes from the file. This is the last unread record.
  5. Set $last = $prev and $next = $last.
  6. Repeat from step 3. until you've read as many records as you want, or until $last > $next (i.e. you've reached the beginning of the file).

Replies are listed 'Best First'.
Re: Re: writing to the top of a file
by jepri (Parson) on May 20, 2004 at 15:42 UTC
    You've turned a conceptually simple process into fifteen overly-complicated steps.

    When you think to use linked lists in Perl, you've probably overlooked a better way to do it using Perl's builtin features. Perl is so good at lists and hashes that you don't need a linked list - Perl's arrays can hold variable length elements, and can be manipulated much like linked lists.

    And packed string headers are most definately only a good idea in C. Regards your variable length 'records', you'd be better off keeping an index in a separate file. Much less complexity, and you can just append to the end of both files.

    But CPAN's Tie:: series of modules have probably already implemented the best solutions.

    ____________________
    Jeremy
    I didn't believe in evil until I dated it.