![]() |
B.6 Working with files |
Nearly every application needs to save or read information. In SheerPower, this is done by working with files. This tutorial will walk you through the entire lifecycle of a file: creating it, writing to it, and reading it back, all while highlighting SheerPower's powerful and efficient features.
Before you can work with a file, you must first
open it. The OPEN
statement establishes a
connection and gives you a file handle—a
temporary nickname, always starting with #
, that you
will use to refer to that file.
When you open a file, you must tell SheerPower *how* you want to use it. This is called the access mode.
Let's walk through the full process of creating a simple settings file.
We'll OPEN
a new file for `output` and use
PRINT #
to write lines of text into it.
This is the most important step! You must always
CLOSE
a file when you are done. This saves your
changes to the disk and releases the file handle.
Now we can reopen the file for `input` to read the data back. We use
a DO/LOOP
and the line input
statement to
read the file one line at a time until we reach the end.
name '@data.txt'
). The `@` is a
special character that always refers to the directory where your
program is currently running. This ensures your code can find its
files no matter where you move it.
What happens if you try to open a file for `input` that doesn't
exist? Your program will stop with an error. To prevent this, you
can wrap your code in a WHEN EXCEPTION IN
block to
catch potential errors and handle them gracefully.
OPEN
a file with the correct
access mode to get a handle.PRINT #
to write or
line input #
to read.CLOSE
the file when you are
finished.WHEN EXCEPTION IN
to handle
potential errors safely.
Hide Description
|
|
Enter or modify the code below, and then click on RUN |
Looking for the full power of Sheerpower?
Check out the Sheerpower website. Free to download. Free to use. |