Page 1 of 1

readln() for a certain line

Posted: February 7th, 2005, 1:44 pm
by byronnash
When using the readln() method, how can I have it skip to a certain line? I don't want to have to readln() a bunch of extra lines if I know I need to read lines 11 -123 for example.

Posted: February 7th, 2005, 2:44 pm
by vidpat
If all of the lines have have the same number of bytes or if line 11 (per the example) is always n many bytes from the start of the file, you could use seek(). Otherwise, readln() seems like the best approach. A little function goToLine() could be helpful:

Code: Select all

function goToLine(fileF /* open File object */,
        lineI /* line number to go to */,
        relativeB /* boolean to start from current position */) {
    // If we don't want to skip lines relative to our
    //  current position in the file, reset the position
    //  to the beginning of the file.
    if (!relativeB) { fileF.seek(0, 0); }
    // Read through lineI - 1 lines to position at the
    //  start of the desired line.
    for (var i = 0, i < lineI, i++) {
        fileF.readln();
    }
}
Peter

Posted: February 8th, 2005, 6:44 am
by byronnash
Thanks Peter, that worked like a charm.