Finding+the+last+character+read+from+a+file

//by Richard Russell, January 2012//

Occasionally you may want to find out what was the last character read from a file (without the overhead of backspacing the file pointer and reading it again). For example, if you read a string from a file using [|GET$#] it may be useful to know whether the string was terminated by **CR**, **LF** or **NUL**.

Because of the way //BBC BASIC for Windows// buffers files in memory (to increase speed of access) it is possible to discover the last character read by examining the contents of the buffer. This function does it: code format="bb4w" DEF FNlastfilechar(F%) LOCAL B%, B&     IF F%<5 OR F%>12 THEN = -1 B% = @hfile%(0) + (F%-5)*&100 B& = ?(^@hfile%(F%) + 32) - 1 = B%?B& code The parameter is the file channel number (as returned from [|OPENIN] or [|OPENUP]) and the value returned is the last character read or **-1** if the supplied channel number is invalid. If an attempt was made to read beyond the end of the file, the returned value is undefined.

The function will only work reliably if the last operation on the file was a read (e.g. using **BGET#**, **GET$#** or **INPUT#**). It can be used only with //files//, not with //ports//.