Is it possible to parse file from end to beginning?

egoregor Moscow
edited January 2019 in RAPID Programming
 I can read and parse txt file from the beginning to the end this way:

Open "HOME:/Test.txt",file\Read;
Rewind file;

But how to read the file in reverse order? Is it possible using "ReadStr" function?


  • soupsoup USA ✭✭✭
    You could probably count the lines of the file with a FOR loop from beginning until EOF, then use ReadStr with \Line to start with the last line and FOR loop from the last line to the first line.
  • soupsoup USA ✭✭✭
    Seemed to work -- as long as the line is not too long and can fit into a single string...

    PROC exampleReadFileInReverse()
            VAR string text;
            VAR iodev infile;
            VAR num lineCounter:=0;
            Open "HOME:/test.txt",infile\Read;
            ! count number of lines in the file
            WHILE text <> EOF DO
                IF text <> EOF THEN
                    text := ReadStr(infile\Line:=lineCounter+1);
                    IF text <> EOF lineCounter:=lineCounter+1;
            TPWrite "File has "+NumToStr(lineCounter,0)+" lines.";
            ! read file in reverse
            FOR i FROM lineCounter TO 1 STEP -1 DO
                text := ReadStr(infile\Line:=i);
                TPWrite "Line #"+NumToStr(i,0)+" = "+text;
                WaitTime 1;


  • egoregor Moscow
    soup said:
    Seemed to work -- as long as the line is not too long and can fit into a single string...
    Thanks for answer! I will definitely try your code. I figured out how to solve the problem through a temporary array. It's working with any amount of strings in file.
  • soupsoup USA ✭✭✭
    Looks good.

    To clarify: I was stating that you'd have a problem if a single line is long, rather than a large quantity of lines -- make a test line with a hundred chars to see what I mean.

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!