: 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.
Comments
:
: 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.