Sequential File I/O

19.1 Opening and closing files

read text sequentially (file must exist) write text, replacing existing contents write text at the end read/write bytes at any position (Chapter 20) fixed-length records (Chapter 20)

Use FREEFILE to get an unused file number: f = FREEFILE: OPEN name$ FOR INPUT AS #f.

CLOSE with no number closes all open files.

Old GW-BASIC syntax OPEN "O", #1, "notes.txt" (modes "I", "O", "A", "R", "B") still works.

OPEN "notes.txt" FOR OUTPUT AS #1     ' create or overwrite
PRINT #1, "First line"
PRINT #1, "Second line"
CLOSE #1

OPEN "notes.txt" FOR APPEND AS #1     ' add to the end (creates the file if missing)
PRINT #1, "Appended line"
CLOSE #1

OPEN "notes.txt" FOR INPUT AS #1      ' read
DO UNTIL EOF(1)
    LINE INPUT #1, ln$
    PRINT ln$
LOOP
CLOSE #1

19.2 PRINT #, WRITE #, INPUT #, LINE INPUT #

WRITE # is the natural partner of INPUT # because it quotes strings (so commas inside names survive).

LINE INPUT # reads the entire line as one string — use it for arbitrary text.

PRINT # USING formats output like PRINT USING.

' Writing structured records
OPEN "scores.csv" FOR OUTPUT AS #1
WRITE #1, "Ada", 970, 12.5        ' "Ada",970,12.5   — quoted strings, commas
WRITE #1, "Grace, Admiral", 880, 9.75
PRINT #1, "Linus"; ","; 750; ","; 8   ' PRINT # writes exactly what PRINT would show
CLOSE #1

' Reading them back
OPEN "scores.csv" FOR INPUT AS #1
DO UNTIL EOF(1)
    INPUT #1, nm$, score, timeTaken  ' INPUT # splits on commas, removes quotes
    PRINT nm$, score, timeTaken
LOOP
CLOSE #1

19.3 File and directory commands

Statement / function true at end of file length of file in bytes current position (last record/byte read or written) delete a file (wildcards allowed — careful!) NAME "old" AS "new" rename or move a file MKDIR, RMDIR, CHDIR create, remove, change directory FILES "*.bas" list files on screen _FILEEXISTS(f$), _DIREXISTS(d$) existence checks (QB64) _STARTDIR$, _CWD$ program start directory, current directory (QB64)

Classic BASIC: cassette and disk files used OPEN 1,8,2,"NAME,S,W" (Commodore), PRINT#, INPUT#, GET#; Applesoft used DOS commands printed with CHR$(4). GW-BASIC is nearly identical to QBasic. FreeBASIC: same statements; Open ... For Input Encoding "utf8" As #1 for Unicode text; Open can be used as a function returning an error code. VB.NET: System.IO: File.ReadAllLines(path), File.WriteAllText(path, text), File.AppendAllText, Using sr As New StreamReader(path) ... sr.ReadLine() ... End Using, Directory.GetFiles, Path.Combine. TextFieldParser handles CSV.