RetroCoders Community

FreeBasic Programming => FreeBasic Tips & Tricks => Topic started by: ron77_db on Apr 11, 2022, 05:26 PM

Title: a function that prints whole text file on screen
Post by: ron77_db on Apr 11, 2022, 05:26 PM
this little function will read the text in the text file and will print it to the console/screen

'improve print of whole text file on screen
SUB txtfile(f AS STRING)
CLS
DIM AS STRING buffer
DIM h AS LONG = FREEFILE()
if OPEN(f FOR BINARY access read AS #h) then
print "file could not be opened!"
elseif (lof(h) < 1) then
print "file could not be read!"
else
buffer = SPACE(LOF(h))
GET #h ,  , buffer
CLOSE #h
PRINT buffer
end if
End SUB
Title: Re: a function that prints whole text file on screen
Post by: __blackjack__ on Aug 05, 2025, 07:00 PM
The ELSEIF test doesn't make much sense, the message is wrong because there wasn't even an attempt to read the data, and the file isn't closed properly in that case.

If empty files should lead to a message, then just check the length of BUFFER:
SUB PrintTextFile(filename AS STRING)
    DIM buffer AS STRING, handle AS LONG = FREEFILE
    CLS
    IF OPEN(filename FOR BINARY ACCESS READ AS #handle) THEN
        PRINT "File could not be opened!"
    ELSE
        buffer = SPACE(LOF(handle))
        IF LEN(buffer) = 0 THEN
            PRINT "File is empty."
        ELSE
            GET #handle, 0, buffer
        END IF
        CLOSE #handle
        PRINT buffer;  ' Prints nothing if file was empty.
    END IF
END SUB