files with pointers/linklists - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

files with pointers/linklists

easlereasler Posts: 1Member
Hey guys!

How do I read in a file using pointers? I'm just beginning to program and I am a little confused on this.

Thanks.

Comments

  • zibadianzibadian Posts: 6,349Member
    : Hey guys!
    :
    : How do I read in a file using pointers? I'm just beginning to program and I am a little confused on this.
    :
    : Thanks.
    :
    This involves two steps:
    1st you need to create the poiner using GetMem() or New().
    2nd you need to read the value into the dereference pointer.

    Example:
    [code]
    type
    MyIntPtr = ^integer;
    var
    i: MyIntPtr;
    f: text;
    begin
    MyIntPtr := New(MyIntPtr);
    Assign(f, 'somefile.dat');
    Reset(f);
    read(f, i^); { dereferenced pointer }
    close(f);
    end;
    [/code]
    A linked list is similar, but a little more involved:
    [code]
    type
    PIntegerItem = ^TIntegerItem;
    TIntegerItem: record
    Value: integer;
    Next: PIntegerItem;
    end;
    var
    List, Current: PIntegerItem;
    f: text;
    begin
    Current := nil; { Make sure current is nil }
    Assign(f, 'somefile.dat');
    Reset(f);
    while not eof(f) do begin
    if Current = nil then begin { Reading first value }
    Current := New(PIntegerItem);
    List := Current;
    end else begin { Reading second and further values }
    Current^.Next := New(PIntegerItem);
    Current := Current^.Next;
    end;
    read(f, Current^.Value); { Actual reading }
    end;
    close(f);
    end;
    [/code]
    I highly recommend that you do NOT save and read the actual pointer values, because these might be different each time the program runs.
Sign In or Register to comment.