Re: read text file, assign command


Posted by webmaster Guido on June 22, 2000 at 19:47:40:

In Reply to: read text file, assign command posted by Kreso on June 22, 2000 at 15:37:50:

: I get an error message:"incompatible TPerssistant and Text" when I try to assign a file to a program!If somebody knows how to do that please tell me.
: that part goes something like this:

: var
: ATextFile: Text;
: ATexrLine,
: AFileName: String;
: begin
: AFileName:='file.txt';
: Assign(ATextFile,AFileName);
: Reset(ATextFile);
: while not Eof(ATextFile) do begin
: whats wrong!?!

------------------------------------------------

Try this:

var
  ATextFile: TextFile;
  ATextLine, AFileName: String;
begin
  AFileName := 'file.txt';
  AssignFile(ATextFile, AFileName);
  Reset(ATextFile);
  while not Eof(ATextFile) do begin
    Readln(ATextFile, ATextLine);
    // do something with the textline:...
  end;
  CloseFile(ATextFile);
end;
Note: if your textfile is not too long (I tried it with files of several tenthousands of lines), you can code it as follows:
var
  SL: TStringList;
begin
  SL := TStringList.Create;
  SL.LoadFromFile('file.txt');
  // do something with the text lines:...
  // ...
  SL.Free;
end;

This is a lot more flexible: quickly read the file, then do whatever you want, e.g. sorting alphabetically is as simple as:
SL.Sorted := TRUE;