a function that prints whole text file on screen

Started by ron77_db, Apr 11, 2022, 05:26 PM

Previous topic - Next topic

ron77_db

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

__blackjack__

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
Two is the oddest prime.