Reading — step 1 of 4
Learn
~2 min readOOP, Pointers, File I/O
BASIC's file I/O dates from the 1960s — surprisingly clean.
Sequential read
DIM line_buf AS STRING
OPEN "data.txt" FOR INPUT AS #1
DO WHILE NOT EOF(1)
LINE INPUT #1, line_buf
PRINT line_buf
LOOP
CLOSE #1
The #1 is a file number — like a file descriptor. Pick any number 1-255.
Sequential write
OPEN "output.txt" FOR OUTPUT AS #1 ' truncates existing
PRINT #1, "hello"
PRINT #1, "world"
CLOSE #1
OPEN "output.txt" FOR APPEND AS #1 ' append mode
PRINT #1, "appended"
CLOSE #1
Random / binary access
OPEN "data.bin" FOR BINARY AS #1
DIM buf AS STRING * 256
GET #1, , buf ' read 256 bytes
CLOSE #1
The STRING * 256 creates a 256-byte fixed-length string.
File modes summary
INPUT— read textOUTPUT— write (truncate)APPEND— write at endBINARY— read+write raw bytesRANDOM— fixed-record-size files (legacy)
Error handling
DIM error_code AS INTEGER
OPEN "missing.txt" FOR INPUT AS #1
IF ERR <> 0 THEN
PRINT "can't open: error "; ERR
END IF
The ERR function returns the last error code (0 = no error).
For cleaner handling:
IF (FREEFILE = 0) THEN
PRINT "no free file numbers"
ELSE
DIM f AS INTEGER = FREEFILE ' get an unused number
OPEN "data.txt" FOR INPUT AS #f
' ...
CLOSE #f
END IF
FREEFILE returns the next available file number — avoids manually tracking.
stdin / stdout
For scripts:
INPUT "", varreads a line and parsesLINE INPUT "", varreads a raw line (no parsing)PRINTwrites to stdout
For testing on Judge0: use INPUT and LINE INPUT for stdin reading.
OS commands
DIM exit_code AS INTEGER
exit_code = SHELL("ls -la") ' run external command
FreeBASIC additions
FreeBASIC has more modern functions:
FILEEXISTS(path)— does file exist?KILL path— delete fileNAME old_path AS new_path— renameMKDIR path,RMDIR pathCHDIR path,CURDIR()
Environment variables
DIM home AS STRING = ENVIRON("HOME") ' or "USERPROFILE" on Windows
PRINT home
Why file I/O in BASIC
- BASIC was made for hobbyist programs that read/write text files
- The PRINT/INPUT pairing makes simple text I/O dead easy
- Game saves, configuration files, log files — straightforward
For structured I/O (XML, JSON), use FreeBASIC libraries or roll your own parser. The standard library doesn't have JSON support built-in.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…