RobotStudio event

Is it possible to parse file from end to beginning?

egor
egor
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;
WHILE EOF=TRUE DO
Read_Str:=ReadStr(file);
ENDWHILE

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

Answers

  • soup
    soup ✭✭✭
    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.
  • soup
    soup ✭✭✭
    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
            lineCounter:=0;
            WHILE text <> EOF DO
                IF text <> EOF THEN
                    text := ReadStr(infile\Line:=lineCounter+1);
                    IF text <> EOF lineCounter:=lineCounter+1;
                ENDIF
            ENDWHILE
           
            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;
            ENDFOR

        ENDPROC

  • 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.
  • soup
    soup ✭✭✭
    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.