|
Working with Console Output, Text Files, URL Data, and Text Windows |
Nearly every application needs to save or read information. In Sheerpower, files—local, in-memory, or remote—are all handled through the same simple text-based I/O model. This tutorial walks you through the entire lifecycle of a file: creating it, writing to it, and reading it back, while highlighting Sheerpower's 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
nickname you will use to refer to that file.
The print statement outputs data to any open file that
permits writing.
In Sheerpower, console output uses channel #0, which
is always open by default. A print statement without an
explicit channel automatically targets the Sheerpower console. If a
program never prints to channel #0, the console
window is never created, allowing applications to run fully headless
without appearing on the operating system task bar.
Efficiency:
Sheerpower print statements use internal buffering with
lazy writes rather than constructing temporary string objects. This
design eliminates allocation overhead and avoids garbage collection
pressure during output operations.
When you open a file, you must tell Sheerpower how you want to use it. This is called the access mode.
shared ideal for
log files that are being watched as a program runs.
Problem: In many applications, log files don't display new entries until the buffer fills or the file is closed, making real-time monitoring unreliable.
Solution: Sheerpower's shared access
mode automatically flushes writes often enough that other processes can
see updates almost immediately—without requiring extra code.
Efficiency: Instead of flushing on every write (which wastes I/O), Sheerpower uses a timed cycle, balancing responsiveness with performance.
Takeaway: Use shared mode when you need
log files or outputs that remain live and visible as your program runs,
with no extra effort.
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.
Sheerpower simplifies a common task: writing the exact same information
to multiple places simultaneously. Instead of writing separate
PRINT statements for each destination, you can list all the
file handles in a single, efficient command.
A frequent use case is logging an event to both the user's screen (the console) and a permanent log file. Sheerpower makes this trivial.
When you run this code, the message
INFO: System backup completed successfully. will appear on
your screen and will be added to the end of the activity.log
file.
Problem: When you need to send the same output to
multiple places (like console and log files), writing separate
PRINT statements clutters your code and risks mistakes.
Solution: Sheerpower allows you to list multiple
file handles in a single PRINT statement, ensuring the
exact same content is written everywhere at once.
Efficiency: This approach is cleaner and less error-prone, reducing duplication while making your intent obvious at a glance.
Takeaway: Use multi-handle printing whenever you need to mirror the same message to several destinations—it keeps your code concise, reliable, and easy to maintain.
Sometimes a program needs to display information in a separate pop-up window — for example, a running event log, diagnostic trace, or real-time message stream. In Sheerpower, you can do this easily by opening a textwindow instead of a disk file.
A textwindow behaves like any other output channel, except that its contents appear in a new on-screen text window. This makes it useful for rare or important messages that you want to keep visible while the program continues running.
To create one, use the OPEN statement with a
name beginning with "textwindow://".
The text immediately following textwindow:// becomes
the window title. Optional parameters, such as the window width,
may be added after a ?.
// Opens a text window titled "My EventLog" with a width of 120 columns open file event_ch: name "textwindow://My EventLog?width=120", access output print #event_ch: "I just opened the event logging text window" print #event_ch: "Logging continues as the program runs..."
Once opened, the text window stays active until closed by the program
or by the user. You can write to it just like any other file handle
— using PRINT #.
textwindow:// channel creates an independent
on-screen text window, optionally labeled with a clear title.textwindow:// when you want important messages or
diagnostics to remain visible throughout program execution.
textwindow:// to open a live on-screen text window.
textwindow:// becomes the window title.
?width=120 after the title.
PRINT # just like a normal file.
After completing your work with a file, it's good practice to
close it explicitly using the CLOSE statement.
This ensures that all data written to the file is properly saved to disk
and that system resources are released immediately.
Although Sheerpower automatically closes any open files when the program ends, closing them manually is more professional — especially for longer-running programs, web services, or applications that open multiple files over time. It prevents file locks, buffering delays, and potential conflicts with other processes trying to access the same files.
You can close one or more file handles at once by listing them after
CLOSE, separated by commas. You can also use
CLOSE ALL to close every open file in one command.
CLOSE for specific file channels when
you're done writing, or CLOSE ALL to ensure every file is
saved and released.
CLOSE #handle to safely finish writing and
release a file.CLOSE ALL closes every open file.
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.
done?, at_end?).
The EOF keyword is what matters: it tells Sheerpower to set your
chosen variable to true when the end of the file is reached.
@data.txt
will always point to data.txt in the same folder
as your running program. This ensures your code finds its files
reliably, without hardcoded paths.
When your project spans multiple directories, Sheerpower provides a simple way to keep paths organized: logical names. These are aliases that map to full directory paths, keeping your file operations clean and making path changes trivial.
Problem: Hardcoded paths like
'd:\apps\projects\common\my_testdata\'
scatter throughout your code, making it painful to reorganize directories
or move projects between machines.
Solution: Define the path once as a logical name. Every file reference uses the short, readable alias. Need to change the directory? Update one line.
Efficiency: Logical names let you group paths by purpose—one for data, another for logs, another for configuration— making your code self-documenting and environment-independent.
Takeaway: Logical names are a built-in, language-level mechanism for centralized path management—simple, powerful, and deployment-friendly.
What happens if you try to open a file for input that does
not exist? By default, the program stops with an error. To prevent
this, you can wrap the operation in a
WHEN EXCEPTION IN block to catch the error and handle it
gracefully.
Sheerpower includes a comprehensive error handling facility. For a detailed discussion, see the Exception Handling tutorial.
Unlike languages that require a separate library for HTTP access, Sheerpower lets you open URLs using the same file commands you use for local text files. This unified design means a program can read from a web resource just as easily as it reads from a file on disk.
open file url_ch: name "https://sheerpower.ttinet.com/index.html".open file url_ch: name "https://sheerpower.ttinet.com/report.csv?user=dan&year=2025".By treating URLs as standard text files, Sheerpower removes the need for specialized HTTP or REST libraries. File and network I/O share the same syntax and behavior, simplifying code, reducing dependencies, and making it easier to build programs that blend local and web-based data seamlessly.
data:// In-Memory File Feature
Sheerpower supports in-memory file channels using the
data:// scheme. These behave like ordinary files but store
their data entirely in memory. This makes them ideal for temporary output,
formatted data generation, or CGI responses that don't require disk access.
open file data_ch: name 'data://'print #data_ch:ask #data_ch: data mydata$mydata$.close #data_chdata:// channels to perform full
file I/O entirely in memory.data:// behaves like a normal file,
but it exists only in memory.
To reset the contents of a data:// channel without closing and
reopening it, use the SET statement:
This clears all accumulated data in the memory buffer, making the virtual file empty again and ready for reuse.
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.OPEN command.data:// feature provides an
in-memory file channel for fast, temporary data
storage and retrieval — no disk access required.OPEN to create a file handle (prefix #)
for working with a file.output (overwrite),
append (add to end), input (read-only),
update (read/write), and shared (timed flush
for log files).PRINT #, read with line input #,
and close with CLOSE # when finished.PRINT statement.@ in file paths for portability across directories —
it always points to the current program's folder.OPEN exactly like text files,
allowing access to web data or RESTful APIs with no extra libraries.data:// feature provides an in-memory file channel
for fast, temporary data storage and retrieval without touching disk.
Use ASK and SET to read or clear it.OPEN just like files,
making it easy to log or display messages interactively.WHEN EXCEPTION IN to handle missing or inaccessible
files safely without program crashes.|
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. |