How to work with records using file stream I/O instead of the 'old' I/O

好久不见. 提交于 2021-02-11 12:03:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!