Search code examples
delphidelphi-7text-files

How to fix issue when loading CR only delimited File text in Delphi 7 ?


I have a big text file (about 100MB) and each lines are separated by CR character, and not CRLF.

I tried to read this text file, line by line using TStringList.LoadFromFile() or ReadLn(F,..), but both methods require the lines are separated by CRLF.

Do you have any efficient and fast method to read this kind of text file?

Thanks.

PS: I am using Delphi 7.


Solution

  • This should do it. Read the text file into a memory stream. Then fill the string list with the contents. textList.Text accepts any combination of CR,LF and CRLF to form a line.

    function MemoryStreamToString( M : TMemoryStream) : string;
    begin
      SetString( Result,PChar(M.Memory),M.Size div SizeOf(Char)); // Works in all Delphi versions
    end;
    
    var
      memStream : TMemoryStream;
      textList  : TStringList;
    begin
      textList := TStringList.Create; 
      try
        memStream:= TMemoryStream.Create;
        try
          memStream.LoadFromFile('mytextfile.txt');
          textList.Text := MemoryStreamToString( memStream);  // any combination of CR,LF,CRLF interprets as a line
        finally
          memStream.Free;
        end;
        // do something with textList
    
      finally
        textList.Free;
      end;
    
    end;