Pages

Navitron

2016-01-06

Reading and writing temporary files 01

Just because I was asked this question today:
How do you read and write to temporary files in BBC BASIC for Windows?

We shall create one temporary file in program one, which will write a short message and the current time into a text file.  Program two will read the text from this file and display on the screen.

Code for Program one:

     REM this program writes a
     REM temporary text file

     
text1$ = "Hello, this file was created by program 1 @"
     text2$ = TIME$

     REM create the file
     
PRINT "writing temp file"
     PROC_createTempFile( "mytemp.tmp", text1$+text2$ )
     PRINT "done"
     STOP


     
DEFPROC_createTempFile( filename$, text$ )
     REM writes the text into the temp file whose
     REM filename is passed in filename$
     
LOCAL file%
     file% = OPENOUT( @tmp$+filename$ )
     PRINT#file%, text$
     CLOSE#file%
     ENDPROC






Code for Program two:

     REM this program reads from a
     REM temporary text file

     
PRINT "looking for the text file."
     text$ = FN_readTempFile( "mytemp.tmp" )
     PRINT "file contains:"
     PRINT text$
     STOP


     
DEFFN_readTempFile( filename$ )
     REM reads the temporary file and returns the text
     REM as a string
     
LOCAL file%, temp$
     file% = OPENIN( @tmp$+filename$ )
     INPUT#file%, temp$
     CLOSE#file%
     = temp$



If you need to navigate through Windows file explorer to find the files yourself then you should find that these programs are reading and writing to a folder located at %USERPROFILE%\AppData\Local\Temp

It would certainly be an advantage to delete the file after it has been used.  Also, it would be better if we could deal with unexpected behaviour and variable sized data lengths.

I will look at some improvements to this code in the next post.


No comments:

Post a Comment