End-Of-File Finding

Authors

Publication

Pub Details

Date

Pages

See all articles from QL Hacker's Journal 27

A lot of the programs that I like to write are filters. They take a text file as input, do something to the file, and output the results to a second file. Doing this involves reading a file one line at a time. A way of doing this would be something like this:

 REPeat loop
    INPUT #4,in$
    IF EOF(#4) THEN EXIT loop
    PRINT in$
 END REPeat loop

This algorithm will work, except that it will not output the last line. When I first tried this, I could not figure out why the last line was not being output. It was all based on how I saw the program being executed. I thought that the INPUT statement would read in the end-of-file (EOF) marker and then do a compare. What is really happening is that the last line is read in, then the EOF check is made. Since the file pointer advanced after reading in the last string, it is now pointing at the EOF marker. When the EOF check is done, it returns TRUE and the EXIT loop is done. A better example would be this:

 REPeat loop
    IF EOF(#4) THEN EXIT loop
    INPUT #4,in$
    PRINT in$
 END REPeat loop

This will print out the last line of the file. But, this algorithm also has its faults. It assumes that there is an end-of-line (EOL) marker at the end of the last line. If there was not EOL and only the EOF, an error would occur reading in the last line.

A better routine would read in each character and put the line together while constantly checking for an EOF. Here is an example:

 DEF PROCedure read_line
    in$=""
    REPeat loop
       IF EOF(#4) THEN EXIT loop
       byte$ = INKEY$(#4,-1)
       in$ = in$ & byte$
    END REPeat loop
    RETURN in$
 END DEF read_line

It would be used like this:

next_line$ = read_line

If using Qliberator, you can use the Q_ERR function to locate EOF. Q_ERR can only trap for EOF after the fact. You keep reading through the file until you get an EOF error, which is trapped by Q_ERR. This means that you would check for Q_ERR/EOF after an INPUT statement. An example is:

 Q_ERR_ON "INPUT"
 REPEAT loop
    INPUT #4,in$
    IF Q_ERR = -10 THEN EXIT loop
    PRINT in$
 END REPEAT loop
 Q_ERR_OFF

Products

 

Downloadable Media

 

Image Gallery

Scroll to Top