Random files in BASIC
Date: Around 1995
In BASIC, using random access files, is there a way to find out how many
records are in a file (as in sequential, there is EOF)?
BASIC, like most other programming languages, has no way of knowing how big
a file is: you just read it until you reach the end. Having said that, I
will now contradict myself!
Your operating system (whatever that may be..) probably knows how big each
file is: that information is kept in the file's header and/or the file
system directory. So, if you know how that information is stored AND you
can access the file headers or the directory files, then your BASIC (or any
other language) routine can figure out file sizes.
Many languages offer "hooks" into the operating system that provide, for
example, system time or info on files. You have to check the particular
implementation of your language for your operating system.
Two possible approaches are:
1) Make all files the same length when you first create them
2) You may be able to use an "ON ERROR" statement to catch the end of file
(It has been a while since I have done much with BASIC so I may be
mistaken about this).
A third approach might be to write the number of records to the first
record. Then you could expand the files but, of course, your program would
have to keep track of any increases in file lengths.
I was just perusing my GWBasic manual. It has an LOF(n) function that
returns the number of bytes allocated for the file. If you have a similar
call you can just divide by the number of bytes per record to get the number
Click here to return to the Computer Science Archives
Update: June 2012