Recent

Author Topic: Put text file into memory?  (Read 2562 times)

TRon

  • Hero Member
  • *****
  • Posts: 2435
Re: Put text file into memory?
« Reply #15 on: July 14, 2020, 06:49:04 am »
    To answer the last question posed to me about TStringList, I have reasons for wanting to use an array instead of TStringList. One of those reasons is the fact that I have some lengthy, intricate code that uses many readlns and writelns and I need to convert all that into faster statements. Reading and writing to disk is fairly fast but it's not fast enough for my purposes. The procedures readline and writeline in my new code are very similar to readln and writeln so basically all I have to do is substitue readln with readline etc. and this should make the work easier.
Then I still don't quite understand why you would do it the way you showed with your solution.

It is far from me to question your code, you should use whatever you are comfortable with but I think it can be done in a better way.

If your code already consist out of many readln's/writeln's then using StreamIO is perhaps the better option (I can show that code as well if you like), but the following is based on your example-code:
Code: Pascal  [Select][+][-]
  1. program bettercameupwith;
  2.  
  3. {$MODE OBJFPC}{$H+}
  4.  
  5. uses
  6.   classes;
  7.  
  8. procedure Button13Click;
  9. var
  10.   sl1 : TStringList;
  11. begin
  12.   sl1 := TStringList.Create;
  13.  
  14.   // "Write" _six_ lines of text into the list. Each element of the list represents a line of string text.
  15.   sl1.Append('Four');
  16.   sl1.Append('score');
  17.   sl1.Append('and');
  18.   sl1.Append('seven');
  19.   sl1.Append('years');
  20.   sl1.Append('ago');
  21.  
  22.   // "Read" six lines from an list (simulated text file) and write those same six lines to a test text file.
  23.   sl1.SaveToFile('testfile.txt');
  24.  
  25.   // Shut down the list and return its memory to the system.
  26.   sl1.Free;
  27.   // sound(350);
  28. end;
  29.  
  30.  
  31. begin
  32.   Button13Click;
  33. end.
  34.  
The code is shorter, does not require readln's and writeln's (other than saving or loading the stream itself from and to disk) and you can make as many StringList's as your project requires 'files in memory'. On top of that a stringlist offers indexed access to the individual strings it contains so that in that respect it can be compared to your use of array's.

PS: method looks a bit different then yours because i'm using FreePascal, not Lazarus, and you should be able to copy-paste the relevant parts into a Lazarus project without issues.
« Last Edit: July 14, 2020, 07:06:27 am by TRon »

 

TinyPortal © 2005-2018