Blitz:File Access

From Amiga Coding
Revision as of 19:53, 21 August 2015 by Daedalus (talk | contribs) (Closing Files)
Jump to: navigation, search

Blitz Basic / AmiBlitz provides numerous commands giving you full control over the reading or writing of files. It's generally a simple process, but you should be careful that you're not overwriting something important by accident (such as your own program's source code!), and that you close your files after use or they could remain inaccessible to other programs until you reboot, and could become corrupted in certain circumstances.

The overall process looks like this:

  • Open a file
  • Check if it was opened successfully
  • Direct input from open file or output to open file
  • Read or write information as required
  • Close the file
  • Return input or output to their previous state

Opening Files

Files need to be opened before reading or writing. There are three commands for opening files; which one you use will depend on what you want to do with the file. To open a file you need to provide an ID number which is used to identify the file for later use. Multiple files can be opened at once if you use a unique file ID number for each.

ReadFile

The ReadFile function opens a file for reading. It is a function taking a file ID number and a filename, and will return True (-1) if the file was successfully opened or False (0) if opening the file failed. Possible reasons for failure include the file not existing, the filename being a directory, the file being read protected, file already in use by another program, etc.

Example of use: succ.l = ReadFile(0, "Work:Files/Test.txt")

WriteFile

WriteFile opens a file for writing. If the file exists it will be overwritten without warning! If the file doesn't exist, it will be created as an empty file. Like ReadFile, WriteFile is a function and will return True or False depending on whether it succeeded in opening the file or not. Possible reasons for failure include the volume being write protected, file protected from writing, volume full etc.

OpenFile

OpenFile opens a file for both reading and writing. Again, if the file doesn't exist, it will be created. Existing files won't be overwritten until you write information to them. This command allows full random access of a file, i.e. seeking to a specified point and reading or writing from that point.

Closing Files

Closing files is done with the CloseFile command. Its usage is simply: CloseFile 0 Where 0 is the previously opened file. Always close files after you're finished with them, and remember to redirect your input and output streams elsewhere if necessary.