![]() |
Menu |
QBasic Tutorial #5 So who needs more boring loops. What you will want to do however is read and write to files. These will be stored on the local hard drive or floppy. DIM NewFile$ NewFile$ = "Hello.txt" When run, this will create a file called hello.txt in the same directory as the .BAS which contains nothing at all. Here's how it works. First create a variable that will hold the filename. DIM NewFile$ Now we need a variable to hold a filename. NewFile$ = "Hello.txt" Now the file is opened. As there isn't a file yet, it will create one called hello.txt uses the identifier #1 as a temporary file number (this can be any integer number up to 255). OPEN NewFile$ FOR OUTPUT AS #1 We're not actually going
to do anything to the file so we close it again.
DIM NewFile$ NewFile$ = "Hello.txt" This time, we use the open text file method to open a file to be added (appended) to rather than overwritten. OPEN NewFile$ FOR APPEND AS #1 And now we want to write something to it. The PRINT method adds a carriage return and linefeed to the end. When this file is opened in Notepad then it will display each character on two seperate lines. PRINT #1, "This is saved to the file." Close the file because we've finished. Failure to close a file may result in the file remaining empty or becoming corrupted. CLOSE #1 Running this application more than once will merely append the same letters to the file making it larger and larger. Running the creation program will create a new version that will be empty again. So now to read from the file you've created. Some variables and a reference to the filesystem as before. DIM NewFile$ NewFile$ = "Hello.txt" The file is opened. OPEN NewFile$ FOR INPUT
AS #1 However, if you had appended more than a single line to the file then not all the lines will have been read. This is where a loop comes in handy. DIM NewFile$ DIM Contents$ CLS NewFile$ = "Hello.txt" OPEN NewFile$ FOR INPUT AS #1 DO WHILE NOT EOF(1) INPUT #1, Contents$ PRINT "Read from file: "; Contents$ LOOP CLOSE #1 PRINT "File read!" The new part is the DO loop. It is looking for the End Of File marker (which is specific to the Operating System but you don't need to know what it is) for file number 1 (#1) and it will keep going until it finds it. The first line is pulled into the variable Contents$ and then printed. Then the loop goes around again still searching for EOF. Can't find it so gets the next line (this is all being handled by QBasic for you so no need to track it). Finally EOF is reached (depending on how many lines there are in the file) and it drops out of the DO loop and closes the file and tells the user all is well. There is a bit more to it than that but that is essentially all you need to know to get reading and writing files. Good luck. |
| Written by Nick Cheesman. Last updated: 01/04/2004 Please eMail me at: nickjc@nickjc.co.uk |