Problem na pewno jest w tym, że chcesz zapisać typy string bez podawania ich długości. Trzeba je ograniczyć w ilości znaków albo zapisać wcześniej ilośc tych znaków. Przeanalizuj sobie poniższe kody, a wszystko powinno być jasne. Wprawdzie aplikacja konsolowa, ale to pisane na szybko żeby tylko pomóc zrozumieć ideę działania zapisu oraz odczytu danych.
Przykład pierwszy:
program example1;
{$APPTYPE CONSOLE}
type
TRec = record
Cnt : Byte;
Txt : string[20];
end;
const
AFileName = 'D:\test.bin';
TxtArr : array[1..2] of string = ('raz', 'dwa');
var
I : integer;
AFile : file of TRec;
DataArr : array[1..2] of TRec;
begin
for I := Low(DataArr) to High(DataArr) do
begin
with DataArr[I] do
begin
Cnt := I;
Txt := TxtArr[I];
end;
end;
// Zapis
Assign(AFile, AFileName);
Rewrite(AFile);
for I := Low(DataArr) to High(DataArr) do
Write(AFile, DataArr[I]);
Close(AFile);
// Odczyt
Assign(AFile, AFileName);
Reset(AFile);
for I := Low(DataArr) to High(DataArr) do
begin
Writeln('Rekord numer: ', I);
with DataArr[I] do
begin
Writeln('Pole Cnt: ', I);
Writeln('Pole Txt: ', Txt);
end;
end;
Writeln('Rozmiar pliku (ilosc rekordow): ', FileSize(AFile));
Close(AFile);
Readln;
end.
Przykład drugi:
program example2;
{$APPTYPE CONSOLE}
const
MaxCnt = 6;
AFileName = 'D:\test_2.bin';
TxtArr : array[1..MaxCnt] of string = ('ucz', 'sie', 'podstaw', 'i', 'kombinuj', 'sam.');
var
S : string;
AFile : File of Byte;
I, TxtLength, RecCnt : integer;
DataArr : array[1..MaxCnt] of string;
begin
for I := Low(DataArr) to High(DataArr) do
DataArr[I] := TxtArr[I];
// Zapis
RecCnt := Length(DataArr);
Assign(AFile, AFileName);
Rewrite(AFile);
BLockWrite(AFile, RecCnt, SizeOf(RecCnt));
for I := Low(DataArr) to High(DataArr) do
begin
TxtLength := Length(DataArr[I]);
BlockWrite(AFile, TxtLength, SizeOf(TxtLength));
BlockWrite(AFile, DataArr[I][1], TxtLength);
end;
Close(AFile);
// Odczyt
Assign(AFile, AFileName);
Reset(AFile);
BlockRead(AFile, RecCnt, SizeOf(RecCnt));
for I := 1 to RecCnt do
begin
BlockRead(AFile, TxtLength, SizeOf(TxtLength));
SetLength(S, TxtLength);
BlockRead(AFile, S[1], TxtLength);
Writeln(S);
end;
Close(AFile);
Readln;
end.