Popup YouTube Video
Sheerpower Logo

Working with Files, Console Output, URLs, and Data


A single United I/O Pattern

Working with text files, console output, and URL data is handled through the same simple text-based I/O model.

This tutorial walks you through the full lifecycle of a file: creating it, writing to it, and reading it back. Along the way, it also highlights Sheerpower's efficient text I/O features.

Direct console output: Outputting directly to the console is very simple. Multiple expressions of any data type can be printed in one statement by separating them with semicolons.

my_name$ = "Sally" my_age = 22 print "Hello "; my_name$; ". I see that you are "; my_age; "."

1. The File Handle: Your Connection to a File

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.

Output to a 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.

Your Program
File Handle
(#logfile)
Physical File
(log.txt)
! Open log.txt and get the handle #logfile open file logfile: name "log.txt", access output

2. File Access Modes

When you open a file, you must tell Sheerpower how you want to use it. This is called the access mode.

  • output: Creates a new, empty file for writing. If the file already exists, it will be overwritten.
  • input: Opens an existing file for reading only. This is the default open mode.
  • update: Opens an existing file for both reading and writing.
  • shared: Opens the file so multiple processes can access it at the same time. Writes are automatically flushed to disk quickly enough for other readers to see new data almost immediately, but not so frequently that they create an I/O bottleneck. This makes shared ideal for log files that are being watched as a program runs.

ACCESS OUTPUT Creates Missing Directories

When a file is opened with access output, Sheerpower automatically creates any missing directories in the output path. This means you do not need to manually create the directory tree before writing the file.

For example:

open file log_ch: name "logs\errors\today\error_log.txt", access output print #log_ch: "Program started" close #log_ch

If the logs, errors, or today directories do not already exist, Sheerpower creates them automatically before opening the output file.

Problem: In many languages, writing to a nested file path fails unless every directory in the path already exists.

Solution: Sheerpower's open file ... access output statement creates the required directory tree automatically.

Efficiency: Programs do not need extra setup code, shell commands, or separate directory-checking routines just to prepare log paths, data paths, export paths, or other output locations.

Takeaway: access output lets you write directly to the intended file path, creating any missing output directories automatically. Input files are different: missing paths still raise meaningful exceptions.


More on Shared Mode

Problem: In many applications, a log file does not show new entries right away. Data may remain in a buffer until it fills or the file is closed, making live monitoring unreliable.

Solution: Sheerpower's ACCESS SHARED mode is designed for the common case: one process keeps a file open for writing while other processes read it as it grows. Sheerpower flushes buffered output on an internal timed cycle, so readers see new entries almost immediately — without extra code.

Efficiency: Sheerpower does not flush on every write, which would create unnecessary I/O overhead. Instead, it uses a timed flush cycle that balances responsiveness with performance.

Takeaway: Use ACCESS SHARED when one process writes a log file and others need to monitor it live. Sheerpower manages the flush timing for you.

3. The Lifecycle of a File: A Practical Example

Let's walk through the full process of creating a simple settings file.

Step 1: Write to the File

We'll OPEN a new file for output and use PRINT # to write lines of text into it.

open file settings_ch: name "settings.txt", access output ! Use the file handle to print lines into the file print #settings_ch: "theme=dark" print #settings_ch: "user=admin"

Writing to Multiple Files at Once

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.

print #handle1, #handle2, #handle3, ...: 'your text'

Practical Example: Logging to the Console and a File

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.

! Open a log file to add new entries open file logfile: name "@activity.log", access output ! Define the event message we want to log let event$ = "INFO: System backup completed successfully." ! --- ! Print the message to the console (#0) AND the log file (#logfile) ! in a single statement. ! --- print #0, #logfile: event$ ! Always close the file when done close #logfile

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.

Why It Matters

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.

Outputting to Text Windows

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 ?.

Example: Creating a Simple Event Log Text Window

// 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 #.

Why it matters:
Problem: Traditional console output is easy to lose once the user switches windows or multiple processes are running.
Solution: Sheerpower's textwindow:// channel creates an independent on-screen text window, optionally labeled with a clear title.
Efficiency: No GUI toolkit or window management code is required — Sheerpower automatically creates and maintains the text window.

TEXTWINDOW Option Syntax

TEXTWINDOW options are specified using a URL-style format:

textwindow://title of the textwindow?option1=value&option2=value2...

The part before the question mark is the text window title. The part after the question mark contains the options.

Part Meaning
textwindow:// Identifies the output destination as a text window.
title of the textwindow The title shown in the text window title bar.
? Separates the title from the option list.
option1=value Sets an option to a specific value.
& Separates one option from the next.
noclose A flag option. It does not have a corresponding value. Its presence turns the option on.

For example:

open file log_ch: name "textwindow://Process Log?width=90&height=30&max=5000&noclose", access output

This opens a text window titled Process Log. The window is 90 characters wide, 30 characters high, allows the user to scroll back through up to 5000 lines, and does not include a close button.

The noclose option is different from options such as width, height, and max. Those options require values. noclose is simply included by name:

textwindow://Status Window?noclose

Do not write:

textwindow://Status Window?noclose=true

The option is enabled by being present.


Takeaway: Use textwindow:// when you want important messages or diagnostics to remain visible throughout program execution.
(Show/Hide Sheerpower Text Window Takeaways)

Step 2: Closing Files


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.

Example: Closing one or more files


close #settings_ch, #event_ch close all // Close all remaining open files

Problem: Leaving files open can delay disk writes and keep file handles locked, which can cause issues if another program needs access.
Solution: Use CLOSE for specific file channels when you're done writing, or CLOSE ALL to ensure every file is saved and released.
Efficiency: Closing files immediately flushes any buffers and frees memory.
Takeaway: Good practice is to always close files as soon as they're no longer needed — it's fast and safe.

Sheerpower File Closing Takeaways

  • Use CLOSE #handle to safely finish writing and release a file.
  • Multiple handles can be closed in one statement using commas.
  • CLOSE ALL closes every open file.
  • Closing files prevents locked resources and ensures all buffered data is saved immediately.
  • Best practice: Always close files when they are no longer needed.

Deleting Files with KILL

Sheerpower provides the KILL statement for deleting files. The basic form deletes the specified file:

kill filespec$

If the file does not exist, the normal KILL statement raises an exception. This is useful when the missing file should be treated as a meaningful error.

When deleting a file that may or may not exist, use KILL CONDITIONAL:. This form attempts to delete the file, but does not raise an exception if the file is not found.

kill conditional: filespec$

Problem: Programs often need to remove temporary files, log files, or cached output files before creating new ones. Sometimes a missing file is an error, and sometimes it simply means there is nothing to clean up.

Solution: Use KILL when the file is expected to exist. Use KILL CONDITIONAL: when the file may not exist and deletion should continue without raising an exception.

Efficiency: KILL conditional: avoids the need for extra file-exists checks before deleting optional files.

Takeaway: KILL is strict. KILL CONDITIONAL: is tolerant.


Step 3: Read from the 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.

open file settings_ch: name "settings.txt", access input print "Reading settings from file:" do ! Read one line into the variable setting$ ! The eof? variable will become true at the end of the file line input #settings_ch, eof eof?: setting$ if eof? then exit do ! Stop when we reach the end print " > "; setting$ loop close #settings_ch

Note: The variable name eof? is not special. You can use any Boolean variable name you like, such as done? or at_end?.

The important part is the EOF keyword. It tells Sheerpower which variable to set to true when the end of the file has been reached.

The end of the file is detected only after an input attempt is made. In other words, Sheerpower tries to read the next item first, and then sets the EOF variable if there is no more input available.

4. Smart File Paths and High Performance

Best Practice: Smart File Paths with `@`
To keep your code portable and self-contained, use the @ symbol in file paths. The `@` is a special character that always refers to the directory where your program is currently running.

Example:
open file data_ch: name "@data.txt", access input

No matter where you move your program, @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.

Logical Names: Centralized Path Management

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.

Setting Up a Logical — They Survive Reboots

set system, logical 'testit': value 'd:\apps\projects\common\my_testdata'

Using the Logical

// Reference files in that directory using the logical name open file test_ch: name 'testit:mytest.csv'

Why It Matters

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.

Key Advantages

  • Multiple locations can be managed independently.
  • Team environments can have different setups without code changes.
  • Deployment is trivial—just update the logical definitions.
Under the Hood: High-Performance I/O
Sheerpower automatically optimizes all file operations for maximum speed. You don't have to do anything to enable it! It uses:
  • Buffered Writes: Small writes are grouped together in memory and written to disk in a single, efficient operation.
  • Write-Behinds: Your program can continue executing immediately after a `PRINT #` statement, while the data is written to disk in the background.
  • Read-Aheads: When reading a file, Sheerpower intelligently fetches the next chunks of data before you even ask for them, making `line input` incredibly fast.

5. Playing It Safe: Handling Errors

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 Exception Handling.

// This will fail because the file does not exist when exception in open file fake_ch: name "no_such_file.txt", access input use print "Error: Could not find the file." end when

6. Files and URLs: One Unified Concept

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.

In Sheerpower, a URL is simply another kind of text file. The file name itself can be the URL — for example:
open file url_ch: name "https://sheerpower.ttinet.com/index.html".

All standard URLs are supported, including those with parameter pairs — name/value combinations that appear after a question mark in the URL. For example:
open file url_ch: name "https://sheerpower.ttinet.com/report.csv?user=dan&year=2025".

This makes it straightforward for programs to fetch data directly from websites that provide RESTful APIs.
url$ = "https://api.open-meteo.com/v1/forecast" + "?latitude=40.71&longitude=-74.01&hourly=temperature_2m" open file url_ch: name url$ do line input #url_ch, eof eof?: rec$ if eof? then exit do print rec$ loop close #url_ch

Why It Matters

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.


7. Using the 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://' for i = 1 to 10 print #data_ch: i, sqr(i) next i ask #data_ch: data mydata$ print mydata$ close #data_ch

Explanation

  • open file data_ch: name 'data://'
    Creates a memory-only file channel.
  • print #data_ch:
    Writes data to the virtual file, just like a disk file.
  • ask #data_ch: data mydata$
    Reads all data currently stored in the memory file into the string mydata$.
  • close #data_ch
    Closes the virtual file and releases its memory.
Problem: You need to write or collect data temporarily but don't want to use the file system.
Solution: Use data:// channels to perform full file I/O entirely in memory.
Efficiency: Handles several million writes per second on a modern PC. Completely bypasses disk I/O — ideal for CGI responses, generated reports, or quick test output.
Takeaway: data:// behaves like a normal file, but it exists only in memory.

Clearing In-Memory Data

To reset the contents of a data:// channel without closing and reopening it, use the SET statement:

set #data_ch: data ""

This clears all accumulated data in the memory buffer, making the virtual file empty again and ready for reuse.

Summary: You now know how to manage files in Sheerpower! The key steps are:
  1. OPEN a file with the correct access mode to get a handle.
  2. PRINT # to write or line input # to read.
  3. Always CLOSE the file when you are finished.
  4. Use WHEN EXCEPTION IN to handle potential errors safely.
  5. URLs can be opened and read just like local files using the same OPEN command.
  6. The data:// feature provides an in-memory file channel for fast, temporary data storage and retrieval — no disk access required.
(Show/Hide Sheerpower File Handling Takeaways)
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.