Sheerpower Logo

Working with files


Working with Files: A Step-by-Step Guide

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 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 temporary nickname, always starting with #, 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.

Step 2: Close the File!

You should always CLOSE a file when you are done with it. This saves your changes to the disk. Any open files are automaically closed when the progrm ends.

close #settings_ch

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

4. Smart File Paths and High Performance

Best Practice: Smart File Paths with `@`
To make your code portable, always use the `@` symbol in your file paths (e.g., 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.
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
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.
(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.