Reading from the keyboard, reading and writing files, and writing to standard error.
import io
Most programs have to read something and write something. The io package holds the simplest ways to do it: read one line from the user, read or write a whole file in one go, or work through an open file piece by piece.
The functions that take a file name, such as ReadFile, open and close the file themselves. The functions that take a File* work on a file you opened yourself with os.Open; remember to close it with Close.
Use io for the everyday jobs. For checking whether a path exists, listing folders, deleting or renaming files, go to fs; for building paths, fs.path; for formatted output, fmt.
Things that catch people out:
•
A missing file is not an error here. ReadFile returns an empty string, and Lines returns a vector with one empty string in it, so an empty file and a missing one look the same. When the difference matters, check first with os.Exists.
•
Lines are split on \n only. A file saved with Windows line endings keeps a \r at the end of each line from Lines and Readline; trim the line before comparing it.
•
Sizes are counted in bytes, not characters. Outside ASCII one character takes several bytes, so reading a file in chunks can split a character across two chunks.
•
The text functions work on str, which ends at the first zero byte. Binary files such as images are cut short there, so keep this package for text.
Reading a settings file
A small key = value file is the most common thing a program reads at start up. Lines gives you the file as a vector of lines, so the loop only has to skip blank lines and comments and cut each line at the first =. Warnings about bad lines go to standard error with EPrintln, so they never mix with the program's real output.
io-guide-config.salam
import io
importstrfuncmain:
io.WriteFile("app.conf", "# server settings\nport = 8080\n\nhost = localhost\nworkers = 4\n")
mut settings := HashMap {} asHashMap<str, str>
defer settings.Free()
lines := io.Lines("app.conf")
defer lines.Free()
each line in lines:
if line == ""orstr.StartsWith(line, "#"):
continueend
eq_at := str.IndexOf(line, "=")
if eq_at < 0:
io.EPrintln("skipping a line without '=': " + line)
continueend
key := str.Trim(str.Substr(line, 0, eq_at))
value := str.Trim(str.Substr(line, eq_at + 1, line.Len() - eq_at - 1))
settings.Put(key, value)
endprintln"host:", settings.Get("host")
println"port:", settings.Get("port").ToInt() + 1println"settings read:", settings.Size()
end
Output
host: localhost
port: 8081
settings read: 3
Every value comes back as text; convert it where you use it, here with to_int. Lines returns a fresh vector, so free it with defer as soon as you have it. For a structured format with nesting, use encoding.json or config instead of parsing by hand.
Appending to a log
AppendFile opens the file, adds the text at the end and closes it again on every call, so the log is complete on disk even if the program stops halfway. That makes it a good fit for a log or an audit trail. Both WriteFile and AppendFile return minus one when the file cannot be opened, which is worth checking when the path comes from the user or from a setting.
io-guide-log.salam
import io
funclog(path: str, level: str, message: str):
if io.AppendFile(path, "[" + level + "] " + message + "\n") < 0:
io.EPrintln("cannot write to " + path)
endendfuncmain:
path := "app.log"
io.WriteFile(path, "")
log(path, "info", "server started")
log(path, "warn", "disk is 91% full")
log(path, "info", "request served")
log(path, "error", "database did not answer")
mut problems := 0
lines := io.Lines(path)
defer lines.Free()
each line in lines:
if line.StartsWith("[warn]") or line.StartsWith("[error]"):
problems++
println line
endendprintln lines.Len(), "lines,", problems, "need attention"end
Output
[warn] disk is 91% full
[error] database did not answer
4 lines, 2 need attention
Here WriteFile with an empty string starts a new log each time the program runs. Leave that line out and the log keeps growing across runs.
Reading a large file in pieces
ReadFile and Lines hold the whole file in memory. For a file of hundreds of megabytes, open it yourself with os.Open and read a fixed number of bytes at a time with Read. An empty string means the end of the file. Check the handle against null before using it: that is how os.Open says the file could not be opened.
io-guide-chunks.salam
import io
import os
funcmain:
io.WriteFile("big.txt", "0123456789".Repeat(25))
f := os.Open("big.txt", "rb")
if f == null:
io.EPrintln("cannot open big.txt")
ret1enddefer io.Close(f)
mut total := 0mut chunks := 0untiltrue:
piece := io.Read(f, 64asu64)
if piece == "":
breakend
chunks++
total += piece.Len()
println"chunk", chunks, "has", piece.Len(), "bytes"endprintln"read", total, "bytes in", chunks, "chunks"ret0end
Output
chunk 1 has 64 bytes
chunk 2 has 64 bytes
chunk 3 has 64 bytes
chunk 4 has 58 bytes
read 250 bytes in 4 chunks
The size is in bytes, so a chunk boundary can fall in the middle of a multi-byte character. When you only count or copy bytes this does not matter. When you need whole lines, read with Readline instead, as in the next section.
Processing a file line by line
Readline returns one line at a time without its line ending, so only the current line is in memory. Read the header once, then loop until the empty string that marks the end of the file.
io-guide-csv.salam
import io
import os
importstrfuncmain:
io.WriteFile("sales.csv", "item,qty,price\npen,3,12\nnotebook,2,45\nbag,1,180\n")
f := os.Open("sales.csv", "rb")
defer io.Close(f)
header := io.Readline(f)
println"columns:", header
mut total := 0mut line := io.Readline(f)
until line != "":
cols := str.Split(line, ",")
cost := cols.Get(1).ToInt() * cols.Get(2).ToInt()
println cols.Get(0), cost
total += cost
cols.Free()
line = io.Readline(f)
endprintln"total:", total
end
Output
columns: item,qty,price
pen 36
notebook 90
bag 180
total: 306
One catch: an empty line in the middle of the file also comes back as an empty string, and this loop would stop there. If your files can contain blank lines, compare the position with the file size, or read with Lines when the file is small enough. For real CSV with quoted fields, use encoding.csv.
Reads one line from standard input, usually the keyboard, and returns it without the line ending. It is the same thing input "" does. The example below waits for you to type, so here it is only compiled and not run.
io-Input.salam
import io
funcmain:
print"What is your name? "
name := io.Input()
println"Welcome,", name
end
Reads one line from the file, without the \n at its end (a \r before it stays). At the end of the file it returns an empty string, and so does a blank line, so a loop that stops on "" also stops at the first blank line.
The example for this item is shown with the ones above: io-Read.salam
Moves the reading and writing position in a file. offset is a distance in bytes and whence says where to count from: zero is the start of the file, one is the current position and two is the end. It returns zero on success and minus one on failure.
The example for this item is shown with the ones above: io-Read.salam
Creates the file, or empties it if it already exists, and writes the string into it. It returns the number of bytes written, or minus one if the file could not be opened.
The example for this item is shown with the ones above: io-ReadFile.salam
Adds the string to the end of the file, leaving what was already there alone. If the file does not exist it is created. Like WriteFile it returns a byte count or minus one.
The example for this item is shown with the ones above: io-ReadFile.salam
Reads a file and returns its lines in a vector. The whole text is trimmed first, so blank lines at the end disappear, and so does any indentation on the very first line. A missing file gives one empty line. Release the vector with free when you are done with it.
io-Lines.salam
import io
funcmain:
mut lines := Vector {} asVector<str>
defer lines.Free()
lines.Push("apple")
lines.Push("pomegranate")
lines.Push("grape")
written := io.WriteLines("fruit.txt", lines)
println"wrote:", written, "bytes"
read := io.Lines("fruit.txt")
defer read.Free()
each i, line in read:
println i + 1, line
endend
Writes a string to standard error, without a line break. Errors and warnings belong here rather than in the program's real output.
io-EPrint.salam
import io
funcmain:
println"this goes to standard output"
io.EPrint("warning: ")
io.EPrintln("this message goes to standard error")
print"no line break yet..."
io.Flush()
println""end
Output
this goes to standard output
warning: this message goes to standard error
no line break yet...
Writes out whatever is still sitting in the output buffer. Useful when you have written something with print that has no line ending and want the user to see it at once.
The example for this item is shown with the ones above: io-EPrint.salam
Writes everything left in the file src into the file dst and returns the number of bytes copied. It suits large files, since it never holds the whole file in memory.
The example for this item is shown with the ones above: io-Write.salam