July 2, 2007

Reading through text files in memory

Filed under: Scripting — Marcus Tettmar @ 10:20 am

Looping through a text file is commonly achieved with the ReadLn command in a loop, like the example in the help file:

Let>k=1
Label>start
ReadLn>c:\\\temp\\\test.txt,k,line
If>line=##EOF##,finish
MessageModal>line
Let>k=k+1
Goto>start
Label>finish

This uses a very simple loop and loops through the file one line at a time using the ReadLn command and a counter variable.

An alternative method is to read the entire file into memory and then put the lines into an array. This means seeking through the file becomes faster, and it becomes easier to change individual lines. Use the ReadFile command to read the entire file content into a variable:

ReadFile>c:\\\temp\\\test.txt,TheFileData

We now have a variable called TheFileData containing all the lines in the file. Each line will be separated by a Carriage Return, Line Feed combination (CRLF). So we can now split the file into an array using the Separate command, specifying CRLF as the delimiter:

Separate>TheFileData,CRLF,Lines

Lines_Count now tells us how many lines there are and we can access each line with Lines_1, Lines_2, etc. So here’s the new version of the full script:

ReadFile>c:\\\temp\\\test.txt,TheFileData
Separate>TheFileData,CRLF,Lines
Let>k=1
Repeat>k
  Let>CurrentLine=Lines_%k%
  MessageModal>CurrentLine
  Let>k=k+1
Until>k>Lines_Count