QBasic/Files

In this lesson, we will learn how to create and modify files. In doing so, we will create a portion of a text editor to handle reading and writing files to and from disk - the program won't be complete by the end of this chapter, but will be finished within Advanced Text Output.

Let's start by setting up out main procedure:

As you can see, we are using CASE rather than IF. IF statements can sometimes work better than case statements, but for now, we want to avoid spaghetti code (where there are too many GOTO's).

So far, we don't really have much, but it's a start. We've asked the user what they want to do, and finished 1/3 options. Not so shabby when you put it that way!

The OPEN statement
The open statement allows either reading or writing information from the disk. In general, the open statement follows this pattern:

The file$ determines the filename to use. The FOR portion indicates how the file will be accessed or operated - it may be APPEND, BINARY, INPUT, OUTPUT, and RANDOM. The AS # is the identifier used for the file handle in question - this may be a variable if desired.

Input and output
When you need to access or write content to a file handle, the PRINT and INPUT statements expect a file handle to appear as the first parameter:

In some cases, you need to detect if you are going to reach the end of file - this is performed by the EOF function, which accepts a filehandle that takes input.

Reading the file from disk
We will now add a subroutine to read the complete file from disk, as lines of text, into an string array called text. It is also possible to read a data file full of numerical values (and input these into a number array), however that is a different topic.

Note the code that finds the file 'size', by reading lines one at a time until the End Of File is reached, and the use of 'SEEK' to 'rewind' to the beginning again.

The example above treats the file as type=text. If the file contains numbers (for example, a data array of N integers per line x M lines) these can be read (input #) one at a time, directly into a numeric array. Input will read the numbers one at a time, 'stopping' after each is input. Numbers can be separated by 'anything' (so lines of text will be skipped).

Writing a file to the disk
The function for writing a file to disk is easier:

Part 2: New file
In order to create a new file, you have to open it for OUTPUT, then close it. Example: NOTE: If you accidently open an existing file, all of its contents will be overwritten!