给你两个函数,这两个函数可以对付绝大部分数据的储存。
unit FileUnit;
interface
uses Windows, Classes, SysUtils, Dialogs;
type
PDataStru = ^TDataStru;
TDataStru = record
// 这里为你想要的数据类型
end;
procedure ReadDataFile(Filename: string
DataList: TList);
procedure SaveDataFile(Filename: string
DataList: TList);
implementation
procedure ReadDataFile(Filename: string
DataList: TList);
var
PData: PDataStru;
Buf: array[0..BufSize] of byte
//BufSize 是你的数据类型结构的大小多一点
DataFile: HFile;
ReadNumber: LongWord;
FileSize: DWORD;
StruSize: DWORD;
FilePos: DWORD;
begin
if not fileexists(Filename) then
begin
//showmessage('File is not exists.');
exit;
end;
DataFile := CreateFile(PChar(FileName), GENERIC_READ,
0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if DataFile = 0 then
begin
showmessage('Read file error.');
exit;
end;
FileSize := GetFileSize(DataFile, nil);
StruSize := SizeOf(TDataStru);
DataList.Clear;
FilePos := SetFilePointer(DataFile, 0, nil, FILE_CURRENT);
while (FilePos < FileSize) do
begin
new(PData);
ReadFile(DataFile, Buf, StruSize, ReadNumber, nil);
FilePos := SetFilePointer(DataFile, 0, nil, FILE_CURRENT);
CopyMemory(PData, @Buf, StruSize);
if (StruSize <> ReadNumber) then
break;
if PData = nil then continue;
DataList.Add(PData);
end;
CloseHandle(DataFile);
end;
procedure SaveDataFile(Filename: string
DataList: TList);
var
i: integer;
DataFile: HFile;
WriteNumber: LongWord;
StruSize: DWORD;
begin
DataFile := CreateFile(PChar(FileName), GENERIC_WRITE,
0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if DataFile = 0 then
begin
showmessage('Write file error.');
exit;
end;
StruSize := SizeOf(TDataStru);
SetFilePointer(DataFile, 0, nil, FILE_BEGIN);
for i := 0 to DataList.Count - 1 do
begin
WriteFile(DataFile, DataList^, StruSize, WriteNumber, nil);
if (StruSize <> WriteNumber) then
break;
end;
CloseHandle(DataFile);
end;
end.