问题
Never learnt to work with streams for reading / writing data, instead I'm using the old Pascal way. Now everybody says this is not efficient and I would like to learn the file stream way, but can't really work with the tutorials that are available. I am using Excel to create and manage datasets (big data tables with one or two headers). I save these as *.txt files (tab delimited). These files I read with Delphi to fill my records and arrays, etc. Below a simplified code example of what I am doing now. If it makes sense to replace this by data streams, could somebody give me a code example of how this would work? Thanks - Fred
Type
TMyRecord = record // in reality my record file is more complex
ID : integer;
Tekst : string;
R1 : char;
end;
Procedure TForm1.FormCreate(Sender: TObject);
var
MainDir : string; // local directory of the executable
Tfile : textfile;
Fname, T : string;
N : integer;
C : char;
MyData : TMyRecord;
begin
MainDir := GetCurrentDir;
Fname := MainDir + '/Data/File1.txt'; // File1.txt = tab delimited text file
AssignFile(Tfile, Fname);
N := 0;
Try
If FileExists(FName) then begin
reset(Tfile);
while not EOF(Tfile) do begin // find number of record lines
readln(Tfile);
N := N + 1; // not used here, but N = total # of records; required to know!
end;
N := N-1; // correct for the header line not used here
Reset(Tfile);
Readln(Tfile); // read the header (no record data), skip
T := '';
while not EOF(Tfile) do begin
Read(Tfile, MyData.ID, C); // C = read the tab
Read(Tfile, C);
while C <> #9 do begin
T := T + C;
Read(Tfile, C);
end;
MyData.Tekst := T;
Read(TFile, MyData.R1);
Readln(Tfile); // proceed to the next line
end;
end;
Finally
closefile(Tfile);
来源:https://stackoverflow.com/questions/61123434/how-to-work-with-records-using-file-stream-i-o-instead-of-the-old-i-o