Sheerpower Logo

Working with Text Files, URL Data, and Text Windows


Working with Text Files: A Step-by-Step Guide

Nearly every application needs to save or read information. In Sheerpower, this is done through text 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 efficient features.


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 that you will use to refer to that file.

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.
  • append: Opens an existing file to add new data to the very end. If the file doesn't exist, it will be created.
  • 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.

Why It Matters

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.

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 in append mode to add new entries open file logfile: name "activity.log", access append ! 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, simply use the OPEN statement with a name beginning with "textwindow://". You can optionally include parameters such as the window title and width.

Example: Creating a simple event log text window


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:
This feature is extremely convenient for programs that need to show background progress, error traces, or logs while the main application continues.

Problem: Traditional console output gets buried once the user returns to other windows or runs multiple processes at once.
Solution: Sheerpower’s textwindow:// channel creates an independent display surface for live text output.
Efficiency: No extra GUI toolkit is needed — Sheerpower automatically manages the text window and scroll buffer.
Takeaway: Use textwindow:// whenever you want to keep diagnostic or event information visible without cluttering the main output console.

Sheerpower Text Window Takeaways

  • Use textwindow:// to open a live text display window directly from your program.
  • You can specify options like ?width=120 or a custom title for clarity.
  • Write to it with PRINT # just like a regular text file.
  • Ideal for event logs, diagnostics, and background process messages.
  • No GUI libraries or setup required — Sheerpower manages the window automatically.

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.

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 eof? variable is not a special name—you can name it anything you like (e.g., 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.

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

when exception in ! This will fail because the file does not exist 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.