QBasic File IO: Random Data File
Sunday, July 6th 2025
When I was a kid, I spent many hours trying to program stuff in QBasic. I was able to do a few basic things with graphics, drawing shapes, etc. Often I look back at these fond memories. But I can't help but think: "If I could teach my kid self one thing about programming what would would it be?" After much thought, I landed on a few things. But I think I would have made use of data files the most. I wanted to build programs to help my brother run his automotive shop or manage our Boy Scout's advancement records. So I thought, why not explore this concept more and see what was possible. So young Matt, here's the one lesson I pass on to you.
There are several ways to write data to files in QBasic. But I think the most useful mode for database like functions is the "RANDOM". With this mode you can retrieve records by "record number".
TYPE Address id AS INTEGER status AS STRING * 1 'A = ACTIVE, D = DELETED contact_name AS STRING * 30 address1 AS STRING * 30 address2 AS STRING * 30 city AS STRING * 30 state AS STRING * 2 zip AS STRING * 5 END TYPE DECLARE SUB PrintAddress (record AS Address) DECLARE SUB InputAddress (record AS Address) CLS dim path as string path = "projects\address-book\ADDRESS.DAT" DIM record AS Address DIM prompt AS STRING * 1 prompt = "Y" DO WHILE UCASE$(prompt) = "Y" PRINT "Adding New Record" CALL InputAddress(record) OPEN path FOR RANDOM AS #1 LEN = LEN(record) DIM count AS INTEGER count = LOF(1) / LEN(record) record.status = "A" record.ID = (count+1) PUT #1, (count+1), record PRINT "Record Added." CLOSE #1 INPUT "Add Another Record? (Y/N)"; prompt LOOP END SUB PrintAddress (record AS Address) PRINT "ID: " + LTRIM$(STR$(record.id)) PRINT "Contact: " + record.contact_name PRINT "Address1: " + record.address1 PRINT "Address2: " + record.address2 PRINT "State: " + record.state PRINT "City: " + record.city PRINT "ZIP: " + record.zip PRINT STRING$(25, "-") + " " END SUB SUB InputAddress (record AS Address) INPUT "Contact: ", record.contact_name INPUT "Address1: ", record.address1 INPUT "Address2: ", record.address2 INPUT "City: ", record.city INPUT "State: ", record.state INPUT "ZIP: ", record.zip PRINT STRING$(25, "-") + " " END SUB
Categories: Programming
Tags: qbasic