一个简单思路,希望对你有帮助
function TForm1.LoadTreeInfoFromFile(AFileName: string): Boolean;
var
ANode, NextNode: TTreeNode;
ALevel: Integer;
CurrStr: string;
s : array[0..255] of char;
F: file;
P: pNodeInfo;
pLevel: PInteger;
I : Integer;
begin
// 严格顺序
Result := False;
if not FileExists(AFileName) then Exit;
AssignFile(F, AFileName);
Reset(F, 1);
try
TreeView1.Items.Clear;
ANode := nil;
GetMem(PLevel, sizeof(Integer));
CurrStr := '';
while not Eof(F) do begin
GetMem(P, sizeof(pNodeInfo));
BlockRead(F, pLevel^, sizeof(Integer));
BlockRead(F, s, 256);
BlockRead(F, P^, sizeof(TNodeInfo));
CurrStr := s;
ALevel := pLevel^;
if ANode = nil then
ANode := TreeView1.Items.AddChild(nil, CurrStr)
else if ANode.Level = ALevel then
ANode := TreeView1.Items.AddChild(ANode.Parent, CurrStr)
else if ANode.Level = (ALevel - 1) then
ANode := TreeView1.Items.AddChild(ANode, CurrStr)
else if ANode.Level > ALevel then begin
NextNode := ANode.Parent;
while NextNode.Level > ALevel do
NextNode := NextNode.Parent;
ANode := TreeView1.Items.AddChild(NextNode.Parent, CurrStr);
end;
end;
FreeMem(PLevel, sizeof(Integer));
finally
CloseFile(F);
end;
Result := True;
end;
function TForm1.SaveTreeInfoToFile(AFileName: string): Boolean;
var
I, j: Integer;
Node: TTreeNode;
F: file;
P : PNodeInfo;
PLevel: PInteger;
NodeText: array[0..255] of char;
begin
// 逐一设置节点,暂时假定每个节点都是有指针的情况
AssignFile(F, AFileName);
ReWrite(F, 1);
GetMem(PLevel, sizeof(Integer));
for I := 0 to TreeView1.Items.Count - 1 do begin
Node := TreeView1.Items.Item;
P := pNodeInfo(Node.Data);
FillChar(NodeText,256, #0);
for j := 0 to Length(Node.Text) - 1 do
NodeText[j] := Node.Text[j + 1];
PLevel^ := Node.Level;
BlockWrite(F, PLevel^, sizeof(Integer));
BlockWrite(F, NodeText, 256);
BlockWrite(F, P^, sizeof(TNodeInfo));
end;
FreeMem(PLevel, sizeof(Integer));
CloseFile(F);
Result := True;
end;