Choose which line "to readln" in text file

May I choose which line to read (readln) in a text file?

If yes, then what is the command?
If no, is there any way better than the following?

VAR i, which_line: integer;
text_file: text;

write('Line to read:'); readln(which_line);

assign(text_file, 'C: ext_file.txt');
FOR i:=1 TO which_line DO readln(text_file, line);


  • : May I choose which line to read (readln) in a text file?
    : If yes, then what is the command?
    : If no, is there any way better than the following?

    If you work with text files then you can only read line by line ( or value by value) so to skip to a particular line you must read through the whole file until you reach the line or value you're seeking. If you open a text file as an untyped one (i.e var f:file; ) then you can use [b]seek[/b] to jump to every position at any time and read from there. That's easy if you have an even line length text, but quite complicated for irregular line lengths...
  • Thanks for the suggestion of using FILE variable and the SEEK function.
    I have a little problem with my another program.

    Let me explain.
    During name creation, if I enter <3 letters, program closes.
    No error in login process.

    [code]PROGRAM test_1;

    USES crt;

    VAR IOcode: integer;
    name, name2: STRING;
    error: boolean;
    save: text;


    assign(save, 'C:save.txt');

    {$I-} reset(save); {$I+}
    IOcode:= IOresult;
    IF IOcode=2 THEN writeln('Create') ELSE IF IOcode=0 THEN writeln('Login');

    write('Name: '); readln(name);

    IF length(name)>=3 THEN BEGIN

    error:= FALSE;

    IF IOcode=2 THEN BEGIN rewrite(save); writeln(save, name); writeln('Done!!!'); delay(500) END ELSE
    IF IOcode=0 THEN BEGIN readln(save, name2) END


    IF length(name)<3 THEN BEGIN error:= TRUE; writeln('>=3 letters please!'); delay(500) END;

    close(save); clrscr

    UNTIL (name=name2) AND NOT error


    Here's a screenshot (not exactly the same as the one above):

    I find out that the error code for File Not Open is 103.
    My informal solution is to change the IF condition from IOcode=2 to IOcode<>0, also place close(save); between {$I-} {$I-}.

    When I create a new name, the program flow is THE SAME as the following;
    assign(save, 'C:save.txt');
    {$I-} reset(save); {$I+} {IOresult=2}
    But I don't know why the exe gives me error code 103 instead of 2.
  • Problem solved, I finally simplify the program and get the following conclusion:
    assign(save, 'C:save.txt');
    {$I-} reset(save); {$I+} writeln(IOresult);
    {$I-} close(save); {$I+} writeln(IOresult);


    2 stands for File not found. 103 stands for File not open.

    To conclude, I need not to close a text file if RESET() results in an error. Otherwise, another error occurs.
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!