If you've been following along, your code has been living a fleeting, ethereal existence—it runs, it calculates, and then it vanishes the second the process ends. That’s fine for a quick logic test, but eventually, you want your data to persist. You want it to survive a power cycle. You want to touch the disk.
The std/fs module: Talking to the hard drive
In many languages, dealing with the file system involves wrestling with arcane C-style file handles, buffering, and praying you don't leak memory. In Skink, we keep it human-readable with std/fs. It’s not just a wrapper; it’s a sanity-saver.
module main
import "std/fs"
fn main() -> int {
// WriteAll takes the path and the content. It’s that simple.
err := fs.WriteAll("config.txt", "name=skink\n")
if err != nil {
print("Well, that didn't go as planned: {err.String()}")
return 1
}
// Read it back. Simple enough, right?
text, rerr := fs.ReadAll("config.txt")
if rerr != nil {
print("Failed to read: {rerr.String()}")
return 1
}
print(text)
return 0
}
Existence, Appending, and Housekeeping
Rarely do you just write and read once. Usually, you're checking if a file exists, appending logs, or cleaning up after yourself.
// Need to know if a file is already there?
if fs.Exists("config.txt") {
print("Found it.")
}
// Appending is safer than rewriting if you're writing logs
err := fs.AppendAll("log.txt", "system heartbeat at 12:00\n")
// And when you're done or need to move things around:
fs.Rename("old.txt", "new.txt")
fs.Remove("temp.txt")
A note on caution: Be careful with WriteAll. It’s a bit of a "nuclear option"—it doesn't ask twice, it just wipes the existing file and replaces it. I’ve accidentally overwritten my fair share of important configuration files in my time. Learn from my mistakes.
Exercises
Don't just take my word for it—get some bits onto that storage medium:
- The Round-Trip: Write a program that creates a file, reads it back immediately, and prints its length using std/str. It’s a satisfying way to confirm your data made the journey.
- The Persistent Log: Write a program that appends a timestamp from std/time to a file. Run it a few times and watch the file grow.
- The Guardrail: Write a program that tries to create a file, but check fs.Exists first—don't overwrite your own work.
Next
When you're ready to start slicing and dicing your text, we'll talk about Strings and text.