File Handling in Qbasic

Codynn
3 Min Read

In QBasic, you can use the OPEN and CLOSE statements to work with files. To open a file for reading or writing, use the OPEN statement followed by the file name, and then specify the mode in which you want to open the file. The OPEN statement has the following syntax:

OPEN pathname FOR mode [AS filenumber]

The pathname is the name and location of the file that you want to open, and the mode specifies how you want to open the file (e.g., for reading, writing, or appending). The filenumber is an optional parameter that you can use to specify a number that you can use to refer to the file in other statements.

Once you have opened a file, you can use other statements to read from or write to the file. For example, you can use the INPUT and PRINT statements to read from and write to a file, respectively.

 Once the file is open, you can use the INPUT and LINE INPUT commands to read data from the file. For example, the following code reads a line from the file and stores it in a variable called line:

LINE INPUT #1, line

You can also use the PRINT command to write data to a file. For example, the following code writes a string to the file:

PRINT #1, "This is a line of text"

When you are done working with the file, be sure to close it using the CLOSE command:

To close a file, use the CLOSE statement followed by the file number (if you specified one when you opened the file) or the file name.

CLOSE #1

Here is an example of how to use the OPEN, INPUT, PRINT, and CLOSE statements to read from and write to a file in QBasic:

'Open the file for reading 
OPEN "C:\myfiles\myfile.txt" FOR INPUT AS #1 

'Read the first line from the file and print it 
INPUT #1, text PRINT text 

' Open the file for writing 
OPEN "C:\myfiles\myfile.txt" FOR OUTPUT AS #1 

' Write a new line to the file 
PRINT #1, "This is a new line in the file." 

' Close the file 
CLOSE #1

Keep in mind that this is just a simple example, and there are many other things that you can do with files in QBasicuch as the ability to read and write data in different formats (e.g. numbers, strings, etc.), and the ability to seek to specific positions within a file. For more information, you can refer to the QBasic documentation or other online resources.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *