Programming Fundamentals/Files/BASIC

files.bas

edit
' This program creates a file, adds data to the file, displays the file,
' appends more data to the file, displays the file, and then deletes the file.
' It will not run if the file already exists.
'
' References:
'     https://www.mathsisfun.com/temperature-conversion.html
'     https://en.wikibooks.org/wiki/BASIC_Programming

DECLARE SUB Main()
DECLARE SUB CreateFile(Filename AS STRING)
DECLARE SUB ReadFile(Filename AS STRING)
DECLARE SUB AppendFile(Filename AS STRING)
DECLARE SUB DeleteFile(Filename AS STRING)
DECLARE FUNCTION FileExists(Filename AS STRING) AS INTEGER

Main()

SUB Main()
    CONST FILENAME = "~file.txt"

    If FileExists(FILENAME) Then
        PRINT "File already exists."
    ELSE
        CreateFile(FILENAME)
        ReadFile(FILENAME)
        AppendFile(FILENAME)
        ReadFile(FILENAME)
        DeleteFile(FILENAME)
    END IF
END SUB

SUB CreateFile(Filename AS STRING)
    DIM C AS SINGLE
    DIM F AS SINGLE
    
    OPEN Filename FOR OUTPUT AS #1
    PRINT #1, "C" & CHR$(9) & "F"
    FOR C = 0 TO 50
        F = C * 9 / 5 + 32
        PRINT #1, C & CHR$(9) & F
    NEXT
    CLOSE #1
END SUB

SUB ReadFile(Filename AS STRING)
    DIM Text AS STRING

    OPEN Filename FOR INPUT AS #1
    DO WHILE NOT EOF(1)
        INPUT #1, Text
        PRINT Text
    LOOP
    CLOSE #1
    PRINT
END SUB

SUB AppendFile(Filename AS STRING)
    DIM C AS SINGLE
    DIM F AS SINGLE
    
    OPEN Filename FOR APPEND AS #1
    FOR C = 51 TO 100
        F = C * 9 / 5 + 32
        PRINT #1, C & CHR$(9) & F
    NEXT
    CLOSE #1
END SUB

SUB DeleteFile(Filename AS STRING)
    KILL Filename
END SUB

'FileExists checks to see if Filename exists and has content.
FUNCTION FileExists(Filename AS STRING) AS INTEGER
    OPEN Filename FOR INPUT AS #1
    FileExists = NOT EOF(1)
    CLOSE #1
END FUNCTION

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own BASIC compiler / interpreter / IDE.

See Also

edit