保存自定义类型数据到文件

高版本直接用tList<reecord>就可以了。
 如果一定要指针的话,可以这样来:



type
  PHumanRecord = ^THumanRecord;

  THumanRecord = record
    szName: array [0 .. 9] of Char;
    nSex: Integer;
    nAge: Integer;
  end;

  THumanListHelper = class helper for TList<PHumanRecord>
  public
    function SaveToFile(const szFileName: String): Boolean;
    function LoadFromFile(const szFileName: String): Boolean;
    procedure ClearBuffer();
  end;

  THumanRecordHelper = record helper for THumanRecord
  public
    function ToString(): String;
  end;

procedure THumanListHelper.ClearBuffer();
var
  p: PHumanRecord;
begin
  p := First();
  FreeMem(p, Count * SizeOf(p^));
  Clear();
end;
  
function THumanListHelper.SaveToFile(const szFileName: String): Boolean;
var
  hFile: THANDLE;
  pBuffer, pIndex: PHumanRecord;
  nIndex: Integer;
begin
  hFile := FileCreate(szFileName);
  if INVALID_HANDLE_VALUE = hFile then
    Exit(FALSE);

  GetMem(pBuffer, Count * SizeOf(pBuffer^));
  pIndex := pBuffer;
  for nIndex := 0 to Count - 1 do
  begin
    System.Move(Items[nIndex]^, pIndex^, SizeOf(pIndex^));
    Inc(pIndex);
  end;
    
  Result := FileWrite(hFile, pBuffer^, Count * SizeOf(pBuffer^)) > 0;
  FileClose(hFile);

  FreeMem(pBuffer, Count * SizeOf(pBuffer^));
end;

function THumanListHelper.LoadFromFile(const szFileName: String): Boolean;
var
  hFile: THANDLE;
  nSize, nCount: Integer;
  pBuffer, pIndex: PHumanRecord;
  nIndex: Integer;
begin
  hFile := FileOpen(szFileName, fmOpenRead);
  if INVALID_HANDLE_VALUE = hFile then
    Exit(FALSE);

  nSize := FileSeek(hFile, 0, FILE_END);
  nCount := nSize div SizeOf(THumanRecord);

  if nCount = 0 then
  begin
    FileClose(hFile);
    Exit(FALSE);
  end;

  Count := nCount;
  GetMem(pBuffer, nSize);

  FileSeek(hFile, 0, FILE_BEGIN);
  Result := FileRead(hFile, pBuffer^, nSize) > 0;
  FileClose(hFile);

  pIndex := pBuffer;
  for nIndex := 0 to nCount - 1 do
  begin
    Items[nIndex] := pIndex;
    Inc(pIndex);
  end;
end;

function THumanRecordHelper.ToString(): String;
begin
  Result := Format('{"Name":"%s", "Sex":"%d", "Age":"%d"}', [szName, nSex, nAge]);
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  p: PHumanRecord;
  i: Integer;
begin
  with TList<PHumanRecord>.Create() do
  try
    for i := 0 to 9 do
    begin
      p := New(PHumanRecord);
      FillChar(p^, SizeOf(p^), 0);
      StrPCopy(p^.szName, i.ToString());
      p^.nSex := i;
      p^.nAge := i * 2;
      Add(p);
    end;

    SaveToFile('e:1.txt');

    for i := 0 to Count - 1 do
      Dispose(Items[i]);
    Clear();


    LoadFromFile('e:1.txt');
    for i := 0 to Count - 1 do
    begin
      ShowMessage(Items[i]^.ToString());
    end;

    ClearBuffer();
  finally
    DisposeOf();
  end;
end;

http://bbs.2ccc.com/topic.asp?topicid=528530

原文地址:https://www.cnblogs.com/findumars/p/6440279.html