Monday, May 23, 2011

Beginning Programming with Just BASIC -- Tutorial 6: File Input and Output



Tutorial 6: File Input and Output

Suppose we want to be able to close a program to go eat supper and come back later. But we want to save all our data. By now you should be familiar with the fact that variables and arrays reset when you close a program.

You can print data to a file. Like this:

input "Give your file a name: "; filename$
open filename$ for output as #save
print #save, "Yotta yotta homina homina jiggabuh."

Some notes about this code: #save is called a handle, and it is used to refer to the output file. Any variable name preceded by a # is a handle, which are used to describe windows in general. So, if you run this program and name your file "output.txt", a new file will be created in the folder that your basic file is saved in named "output.txt," and it will contain a line that says:

Yotta yotta homina homina jiggabuh.

You can also do input files, so you can load a file into your program that you previously saved.

input "What file would you like to open? "; filename$
open filename$ for input as #load
for i = 1 to n
    input data$(i)
next

Here is an example program that allows you to save your work:

[start]
    print "Would you like to (1) write a story, (2) read one you wrote, or (3) exit?"
    input answer
    select case answer
        case 1: goto [write]
        case 2: goto [read]
        case 3: goto [quit]
    end select

[write]
    input "How many lines will your story be? "; n
    dim txt$(n)
    print "Write your story:"
    for i = 1 to n
        input txt$(i)
    next
    input "Enter a name for the file: "; filename$
    open filename$ for output as #save
    for i = 1 to n
        print #save, txt$(i)
    next
    close #save '<- Closes the file afterward
    goto [start]

[read]
    input "What is the file name? "; filename$
    open filename$ for input as #load
    input #load, n
    dim txt$(n)
    for i = 1 to n
        input #load, txt$(i)
        print txt$(i)
    next
    close #load
    goto [start]

[quit]
    end


Some notes about this code: This is a basic example of a program where the user will be producing something (in this case, a story), and then can read it later. Instead of doing it this way, you should look into how to do a file dialog window (it's easier than you might suppose!).

goto [nextTutorial

2 comments:

  1. please we were asked to write a program that would add , multiply and transpose a matrix and am completely locked out on how to even start because am not good with arrays please help me out please

    ReplyDelete