Step 1 of 4 · Reading · ~3 min
Learn
OOP, 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
EOF(0) does not work on piped input
EOF(0) asks the console device whether more input is waiting, and that is
the right question only when a person is typing. When the grader pipes a file
into your program, file number 0 is not the console and EOF(0) is true
before you have read a single line - so a DO WHILE NOT EOF(0) loop simply
never runs. Open the console device yourself and loop on its own file number:
DIM f AS INTEGER = FREEFILE
OPEN CONS FOR INPUT AS #f
DO WHILE NOT EOF(f)
LINE INPUT #f, line_buf
' ... one line per pass ...
LOOP
CLOSE #f
Measured on the grader with three lines piped in: the EOF(0) loop counts 0,
the EOF(f) loop counts 3.
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…