Getting Started
Introduction
Sample Programs
QBasic IDEs
History
Advice
Tools
Mini-Tutorial
Tutorial
Code Snippets

Resources
Web Sites
More Tutorials
Vendors
Books
Magazines
NewsLetters
NewsGroups
Forums
User Groups
Talk Shows
Blogs

GBIC >> QBasic >> Tutorial >> Files

QBasic Information Center Tutorials - Files
These tutorials were written to help you get a quick, but thorough, understanding of QBasic - the scope of the language as well as it's specific capabilities.

Files
QBasic offers several functions that deal with files - adequate to get work done but not as extensive or useful as many other languages.

    • Binary Actions
     bload, bsave, def seg 
    • Access Control    
     lock, unlock 
    • File Access
     open, close 
    • File Status
     freefile, clear, eof, reset 
    • File Management
     kill, name 
    • Write To File
     write, print, print using 
    • Read From File
     input, input$, line input 
    • Random Files
     get, field, put, seek 
    • File Information
     files, loc, lof, fileattr 

File Basics
In order to read or write information from/to a file, the file must first be opened, using the Open command. There are five modes in which a file may be opened - input, output, append, random and binary. The input, output and append modes are typically called sequential mode because a read/write takes place right after the last read/write. Read/write operations can take place anywhere within files opened in random and binary modes.

    open "myfile.txt" for input as #1           # read only
    open "myfile.txt" for output as #1          # write only, file is cleared
    open "myfile.txt" for append as #1          # write only at end of file
    open "myfile.txt" for random as #1 len=80   # fixed length lines
    open "myfile.txt" for binary as #1          # byte-level read/write

File Content
Files generally come in two flavors - text files and binary files.

Text files typically consist of lines - variable length strings followed by a line feed/carriage (LF/CR) return pair of characters. However, some text files consist instead of fixed length strings, called records, without being separated by the LF/CR character pair. Fixed length strings are typically associated with data bases, where the fixed length strings are broken into 'fields' whose combined length equals the fixed length of each record.

Binary files, on the other hand, consist of content consisting of any combination of ASCII strings and binary data. Binary data can be any byte or combination of bytes as determined by the database programmer. Typical binary data might be a single byte representing an integer. Or, it might be two bytes which represent a long integer. Binary files are very popular for storing numerical data because they take up far less storage space and are much faster to load/write.

The following Open modes can be applied to files of any content type, but knowledge of the file content affects how many of the file handling statements are used.

File Modes
In QBasic there are five modes in which a file may be opened. They affect how the file may be read or edited.

  • Input
    Opens a file as read-only. The current position is set to the first byte of the file.

  • Output
    Opens a file as write-only. It first deletes the content of the file and then establishes the current location as the first byte of the file.

  • Append
    Opens a file as write-only. The current position is set to the end of the file - one position past the last byte in the file, so that the next write/print appends the information to the existing content of the file.

  • Random
    Opens a file with both read and write capability. The LEN parameter in the Open statement tells QBasic that the file consists of groups of characters (records) whose format repeats itself every LEN characters.

    Such files do not necessarily consist of lines - where a line feed/carriage return character pair ends each line. Such pairs may be present in a random file, but are not used to define the end of a record.

    A typical use of random files is information storage - databases, where each records consists of fields of fixed length data.

  • Binary
    Opens a file with both read and write capability. In this case, information is not written as text, but as binary characters.

    When reading or writing variables, the number of bytes used depends on the data type of the variables, as shown in the following table.

    • integer - 1 byte
    • long integer - 2 bytes
    • single - 2 bytes
    • double - 4 bytes
    • string - number of bytes equals number of characters in the string

Mode-Sensitive Commands
The mode in which a file is opened is important because it affects how some QBasic commands act on the file. Specifically, these functions work differently depending on the mode in which a file is opened. The following table give the list of mode-specific commands and how each behaves, depending on the mode in which a file is opened.

Data That is Read/Written in Each File Mode
Function Input Output Append Random Binary
input# var(s) n/a n/a record (string) var(s)
input$# char(s) n/a n/a record (string) var(s)
line input# entire line n/a n/a record (string) var(s)
print# n/a var(s) var(s) record (string) var(s)
print# usingn/a formatted var(s) formatted var(s) formatted record formatted var(s)
write# n/a CSV var(s) CSV var(s) CSV record CSV var(s)
get n/a n/a n/a record (string) n/a
put n/a n/a n/a record (string) n/a
loc bytes/128 bytes/128 byte/128 record byte
lock/unlock file file file record(s) byte(s)
seek byte byte byte record byte

In words, here's what happens.

  • input# - returns variable values in Input/Binary modes and a fixed length string in random mode. It does not apply to Output/Append modes.

  • input$# - returns a specified number of characters in Input/Binary modes, a fixed length string in Random mode and does not apply to Output/Append mode.

  • line input# - returns an entire line in all modes. But remember that Random/Binary files typically have no LF/CR pairs so line input# may attempt to read the entire file into a string variable, which will cause an error if the file size is greater than 32K.

  • print# - will write one or more variable values in Output/Append/Binary modes. It can write a single string variable in Random mode. It does not apply to Input mode.

  • print# using - will use a custom format to write one or more variables in Output/Append modes. It can write a single string variable in Random mode. It does not apply to Input/Binary mode.

  • write# - writes one or more variables using a comma separated variable format (includes quotes around strings) in Output/Append modes. It can write a single string variable in Random mode. It does not apply to Input/Binary modes.

  • get - reads a record/variable from a file opened in random/binary mode

  • put - writes a record/variable to a file opened in random/binary mode

  • loc - returns the current position within a file

  • lock/unlock - locks or unlocks a file so that another program on the system cannot edit the file

  • seek - moves the current position within a file

Mode-Insensitive Commands
These file functions, however, work the same regardless of the mode in which a file is opened. These functions are covered in more detail below.

  • lof - length of file in bytes
  • eof - test for end of file
  • fileattr - returns mode of an opened file
  • clear - closes all files and variables
  • reset - closes all files

Commands for Unopened Files
And finally, these file functions work on unopened files. These functions are covered in more detail below.

  • kill - delete a file from your computer
  • name - rename a file and/or move it to new folder
  • freefile - return next unused file number
  • bload - loads a file into memory
  • bsave - copies memory content to a file

bload/bsave Statements
Generally, file handling commands are slow to execute within QBasic. The bload/bsave commands are an exception to the rule. These allow a program to read/write information directly to a file. bsave put memory content into a file. bload loads a file (that was saved using bsave) into memory.

get/put Statements
The get/put statements are used to read/write information into random or binary files. In random files, a specific record is read/written. In binary files, a variable is read/written. Often, in a binary file, the variable to be read/written is a user-defined type.

Closing a File
When a QBasic program ends, QBasic automatically closes all files. However a file can also be explicitly closed within the program using the Close command. Files can be opened/closed in different modes as many times as needed during the execution of a program.

  • close - closes one, several, or all open files. No other action.
  • reset - closes all open files and devices
  • clear - closes all open files and initializes all variables

Reading From Files
In QBasic there are five basic functions which read from a file. These differ primarily in how much data is read - a variable list, a specific number of characters, entire lines, or complete records.

  • input - reads a variable from a file
  • input$ - returns n characters from a file
  • line input - reads an entire line from a file
  • bload - loads a file into memory
  • get - read a specific record/byte(s) into a variable

Writing to a File
There are five functions which provide the ability to write to files, each providing different formatting capabilities.

  • print - writes variables using default formatting
  • print using - writes variables using user-defined format
  • write - writes variables using CSV formatting
  • bsave - writes memory content to a file
  • put - writes to a specific record or byte position

File Position
QBasic can track, or set, the current position in a file, which is where the next read or write will take place. The two functions that provide file positional information are:

  • loc - identifies the current position within a file
  • seek - set/return current file position

File Functions Reference
Here's a quick reference of the available file functions, in alphabetical order.

Unless otherwise noted, these functions operate on $_ by default.

  • bload - copies memory content to a file
        bload "myfile.txt", offset%
        

  • bsave - loads a file into memory
        bsave ""myfile.txt", offset%, length&
        

  • clear - Closes all files, releases all file buffers, clears all common variables, sets variables and array to zero, sets string variables to empty strings and initializes the stack. Can optionally resize the stack.
        clear
        clear ,,2000
        

  • close - closes one, several or all open files or devices
        close #1        # closes a single file
        close #2, #3    # closes two open files
        close           # closes all open files
        
    Note: the # symbol is optional.

  • def seg - sets the current segment address
        def seg = 0
        

    Use before a bload, bsave, call absolute, peek or poke statement. Value is 0-65,535. Def Seg used alone sets current segment address to the default data segment.

  • field - allocates space for variables in a random-access file buffer
        field #1, width% AS var$        # string variables only
        field #1, 30 as a$, 50 as b$    # multiple variables supported
        

  • fileattr - returns the mode in which a file has been opened
        result% = fileattr(1,1)     # returns mode
        

    Mode return values: 1-input, 2=output, 4-random, 8-append, 32-binary

  • files - displays all files in the current directory
        files filespec$        # default filespec is *.*
        files "*.txt"          # list all text files
        
    The list of files it printed to the screen.

  • freefile - returns the next valid unused file number
        open "myfile.txt" for output as freefile   # use directly
        result% = freefile           # save next valid file number
        

    freefile is used to ensure that a program does not try to open a file with an already used number, which would case a program error.

  • get - reads from a file into a variable
        get #1, recordnumber&, variable     # random-access mode
        get #1, bytelocation&, variable     # binary mode
    
        open "myfile.txt" for binary as #1
        get #1, 25, var$                    # gets 25th byte
    
        open "myfile.txt" for random as #1 len=40
        get #1, 25, var$                    # gets 25th record
        

  • input - reads input from file or keyboard
        input ; "prompt:" ; varlist      # input from keyboard
        input #1, varlist                # input from file
        

    Inputs from keyboard must be separated by a comma, followed by pressing the enter key. You do not enter one value, press Enter, then enter the second value.

    Note: Only fixed-length strings may be included in an Input statement or, if used, a variable length string must be the last variable in the list because it will read in all remaining characters in the file (up to the QBasic 32K string length limit).

  • input$# - reads specified number of characters from keyboard or file
        input$(n,#1)       # n = number of characters
        input$(3,1)        # read 3 characters from file #1 (# is optional)
        

  • kill - deletes a file
        kill "c:\temp\test.bat"      # deletes test.bat
        
    Note: the path can be included. Also, note that under Windows this does not send the file to the trash can. It deletes the file permanently.

  • line input - reads a line of up to 255 characters from keyboard or file
        line input ; "prompt" ; var$       # input from keyboard
        line input #1, var$                # input from open file
        

    Note: line input# expects lines to be separated by the line feed/carriage return character pair. If no such pair exists, the entire file will be read into the variable (up to the QBasic 32K string length limit).

  • loc - returns current position within a file: last byte read for binary, number of last record read for random, and byte position / 128 for sequential.
        result = loc(1)    # values assigned per above rules
        
    The byte/128 for sequential file is generally not useful, so this function is typically used for binary or random files.

  • lock - limits/prevents access to an opened file. can be assigned at the record/byte level.
        lock #1      # locks entire file
    
        open "myfile.txt" for random as #1
        lock #1, 25            # locks only record 25
        lock #1, 25-40         # locks records 25-40
    
        open "myfile.txt" for binary as #1
        lock #1, 25            # locks 25th byte
        lock #1, 25-40         # locks bytes 25-40
        

    Note: for sequential files, affects the entire file.

  • lof - returns length of open file (in bytes)
        open "myfile.txt" for input
        result = lof(1)
        

  • name - renames a file or directory
        name "myfile.txt" as "newfile.txt"         # renames a file
        name "c:\test.bat" as "c:\temp\temp.bat"   # rename/move file
        
    Note: the file names may contain full path information. if the second filename is in a new path, the effect is the same as renaming the file and then moving the file to the new folder.

  • open -
        open file$ for mode$  ACCESS  LOCK  as #1 len=reclen%  # syntax
           # file$ can be filename or device
           # modes: append, binary, input, output, or random
           # lock types: shared, lock read, lock write, lock read write
           # default record length for random-access files is 128 bytes
           # default record length for sequential files is 512 bytes
        open "myfile" for input as #1
        open "myfile" for output as #2
        open "myfile" for random as #1 len=80
        

  • print - writes data to screen or file
        print #1, varlist ;         # prints to a file
        print varlist               # prints to screen
        

    Semicolon at end means print immediately after last value. A comma would mean print at end of print zone (14 char wide). No value means print on next cursor line.

  • print using - writes formatted output to screen or file
        print using #1, using format$ varlist ;    # to file
        print using format$ varlist ;              # to screen
        

    Semicolon at end means print immediately after last value. A comma would mean print at end of print zone (14 char wide). No value means print on next cursor line.

    Numeric format specifiers:

              #    Digit position
              .    Decimal point position
              ,    Placed left of the decimal point,
                   prints a comma every third digit
              +    Position of number sign
             ^^^^  Prints in exponential format
              -     Placed after digit, prints
                    trailing sign for negative
                    numbers.
              $$    Prints leading $.
              **    Fills leading spaces with *.
              **$   Combines ** and $$.
    
        

    String format specifiers:

             &    Prints entire string
             !    Prints only the first character
                  of the string
            \ \   Prints first n characters,
                  where n is the number of
          ¦       blanks between slashes + 2.
        

    Literal character format specifiers:

             _    Prints the following formatting character as a literal
                  Any character not in these format specifier lists
                  are prints as a literal.
        

  • put - writes a variable to a file
        put #1, recordnumber&, variable     # random-access mode
        put #1, bytelocation&, variable     # binary mode
    
        open "myfile.txt" for binary as #1
        put #1, 25, var$                    # puts 25th byte
    
        open "myfile.txt" for random as #1 len=40
        put #1, 25, var$                    # puts 25th record
        

  • reset - closes all open files and devices
        reset          # closes all files/devices (no selective)
        

  • seek - returns or sets the position in a file. for random files, position is record number. for all other modes, position is bytes.
        result = seek(1)     # returns position in file #1
        seek (1,124)         # set file position per rules above
        

  • unlock - unlock #1 # unlocks entire file open "myfile.txt" for random as #1 unlock #1, 25 # unlocks only record 25 unlock #1, 25-40 # unlocks records 25-40 open "myfile.txt" for binary as #1 unlock #1, 25 # unlocks 25th byte unlock #1, 25-40 # unlocks bytes 25-40

    Note: for sequential files, affects the entire file.

  • write - writes data to screen or file
        write "hello"      
        write #1, var$
        

    Strings are written in parentheses and all variables are separated by commas.

If you have any suggestions or correction, please let me know.