Docs/Standard library

io

Print and format values, parse numeric strings into Result values, and scan files or standard input.

Import and print#

Print converts its arguments to text and writes them to standard output (stdout), without interpreting them as a format template. Println adds a newline. The current implementation inserts a space only between adjacent non-string values, so include spaces explicitly when combining text and numbers.

Import io in each file that calls it. The package’s printing functions accept variadic values, so a call can contain one value or several. The formatting of each value depends on its concrete type, while Println adds the final newline regardless of whether the last value is a string.

For mixed text and numbers, include separators in strings or use a format template. For example, io.Println("count: ", 3) includes the desired space explicitly. Relying on automatic spacing between every argument would produce different results because the implementation treats strings differently.

Ocean
package main;
import "io";

func main() {
    io.Println("Hello, Ocean!");
    io.Printfln("The answer is {}", 42);
}

The program prints two lines: Hello, Ocean! and The answer is 42. Print would write the same converted arguments without the final newline. Printfln combines placeholder formatting with a newline.

Formatting functions#

io.Printf(format, items...) replaces each {} in the format string with the corresponding argument’s text, then writes the result. Printfln adds a newline. Sprintf returns Result<string>. Templates use {} placeholders in argument order. The number of supplied formatting arguments must equal the number of {} placeholders. If those counts differ, the function returns Result.error instead of a formatted success value. This is not C-style percent formatting.

Each {} in the template consumes the next argument. Ordinary text, including spaces and punctuation, is copied into the result. The formatter requires the number of arguments to match the number of placeholders: too few and too many both return an error Result.

Choose Printf or Printfln for immediate console output. Choose Sprintf when another function needs the formatted string or when you want to store it. The template language does not implement C percent directives or a general collection of width and precision specifiers.

Only unescaped {} consumes an argument. In the runtime template, a backslash before { makes it literal, and two backslashes produce one literal backslash. In an Ocean string literal, write "\\{}" for literal {} and "\\\\" for one output backslash.

Formatting functions reference
FunctionResult
Print(items ...any) Result<int>Writes converted values
Println(items ...any) Result<int>Writes converted values and a newline
Printf(format string, items ...any) Result<int>Writes a formatted message
Printfln(format string, items ...any) Result<int>Writes a formatted message and a newline
Sprint(items ...any) stringReturns converted values as a string
Sprintf(format string, items ...any) Result<string>Returns a formatted message as a string
Ocean
message := io.Sprintf("{} + {} = {}", 2, 3, 5).unwrap();
io.Println(message);

The returned string is 2 + 3 = 5, and Println then writes it followed by a newline. A percent sequence such as %d is ordinary text for these functions, not an integer placeholder.

Parse integers and floats#

io.ParseInt(text string) Result<int> parses an optional leading sign followed by one or more ASCII decimal digits. It supports the complete signed 64-bit range, including -9223372036854775808. Leading zeros are allowed.

io.ParseFloat(text string) Result<float> parses binary64 decimal numbers with an optional sign, optional point, and optional exponent introduced by e or E, whose exponent may also have a sign. At least one digit is required. Examples include .5, 1., and -1.25e2. Case-insensitive nan, inf and infinity, with an optional sign, are also accepted.

A parse succeeds only if the entire input string is a valid number; neither function accepts just a numeric prefix and ignores the rest. Empty input, surrounding whitespace, digit separators, base prefixes, malformed syntax and trailing characters return error Results. Integer overflow and finite float overflow also return errors. Floats round to nearest with ties to even, support subnormals and signed zero, and underflow sufficiently small values to signed zero. Parsing is implemented in Ocean, independent of libc and locale.

Ocean
package main;
import "io";

func main() {
    count := io.ParseInt("42").unwrap();
    ratio := io.ParseFloat("1.25e-2").unwrapOrElse(0.0);
    parsed := io.ParseInt("invalid");
    match(parsed) {
        Result<int>.value(value) => io.Println(value);
        Result<int>.error(message) => io.Println(message);
    }
    io.Println(count, " ", ratio);
}

ParseInt("42") succeeds with 42. ParseFloat("1.25e-2") succeeds with 0.0125; the fallback 0.0 is used only on an error. ParseInt("invalid") reaches the error arm and prints its message. Whitespace is not trimmed automatically, so ParseInt(" 42") is an error.

Handle parsing errors#

ParseInt and ParseFloat report invalid or out-of-range input as a Result.error variant; the parse call itself does not panic for that input. unwrap returns the value or panics with the stored error message; unwrapOrElse returns a supplied fallback on error; unwrapOrZero returns zero(T) on error. Error strings distinguish invalid input from out-of-range input.

Result<T> belongs to the language and needs no import. ParseInt and ParseFloat belong to the standard-library io package and use capitalized exported names. Update the compiler and io source tree together.

String conversion#

Sprint(items ...any) returns the text that Print would write. The implementation handles signed and unsigned integers, floats, booleans, strings, supported arrays, structs, and enums; raw buffers use a placeholder. The default floating-point conversion rounds to two digits after the decimal point. For example, it is intended as readable output, not as a way to serialize every significant digit of a float.

Sprint is useful when you want the same conversion rules as the printing functions without writing to stdout. Integer values are rendered in decimal, booleans as true or false, and strings as their contents. Arrays are rendered with bracketed elements. Mutable i8[] values print as comma-separated decimal bytes, for example [1, 5, 3]. Strings print as text; use bytes -> string to print a byte array as text. Struct formatting uses reflected field names and field values. Enum formatting uses reflection to print qualified variant names and active payloads, for example Event.Load, Event.Key(65), and Event.Click(x: 2, y: 3). Nested values format recursively.

The current floating formatter uses two decimal places, so this API should not be assumed to preserve arbitrary input precision in its default output. It uses exact binary64 conversion with ties-to-even rounding in Ocean, independent of the C locale. A raw buffer is represented by a placeholder rather than traversed as a length-aware collection.

FormatFloat(value float) string instead produces locale-independent text with 17 significant digits for finite nonzero values, suitable for binary64 round trips. It preserves signed zero and handles NaN and infinities; its output is not always valid JSON. Types without a conversion case, such as maps and pointers, produce [unknown type].

Ocean
text := io.Sprint(42);
values := int[]{1, 2, 3};
io.Println(values);

text contains "42". The final statement prints [1 2 3]. The local string and array have their usual owned lifetimes; returning a formatted string gives the caller an independent value.

Output implementation and platform support#

The standard-library io package has no extern declarations. Output uses assembly system calls on Linux (x86-64, AArch64, RISC-V64) and macOS (x86-64, AArch64). Windows x86-64/AArch64 assembly calls GetStdHandle and WriteFile; native Windows executable links include kernel32 (use -lkernel32 when linking saved IR manually). Other architecture/platform combinations report unsupported output. Writes handle partial results and retry Unix interruptions; other output failures return error Results.

The use of system calls inside io does not remove the rest of the executable’s native dependencies. Compiler-generated runtime code and boxed values can still use native libraries and libffi, so an Ocean executable is not automatically a standalone program with no runtime library dependencies.

Input scanning and files#

Most standard-library I/O operations return Result<T> so the caller can handle an operating-system error as an ordinary result. Calling .unwrap() returns the successful value or panics with the error message. Alternatively, use match to handle Result.error in your program. Close() and Setpos() are exceptions: they return no value and panic on failure.

os.Stdin(), os.Stdout(), and os.Stderr() each return Result<os.File>. Standard input is readable. Standard output and standard error are writable and cannot be used as scanner input. os.Open(path, mode) also returns Result<os.File>; the mode controls whether the file can be read, written, created, truncated, or appended to. The table below explains the modes.

Copying an os.File does not open a second independent stream. File values refer to shared native state, including the current byte position, whether the file is closed, and whether EOF has been reported. Closing one copy affects the others. This sharing is specific to the underlying file handle; ordinary Ocean array and map copies still own independent contents.

io.NewScanner(file) creates a buffered text scanner. It panics if the file is binary, closed, or not readable. Use one scanner for a stream and avoid mixing its buffered reads with direct reads on the same file. io.Scan() and io.Scanln() are convenience functions using a shared scanner for standard input.

scanner.Scan(), scanner.Scanln(), and scanner.Scanc(delimiter) return Result<string>. They consume the delimiter but omit it from the returned string. An immediate delimiter therefore gives a successful empty string. Scan() stops at an ASCII whitespace byte, Scanln() stops at newline or EOF, and Scanc() stops at the requested byte or EOF. For a CRLF line ending, Scanln() consumes the LF and leaves the preceding CR in the returned string. Reaching EOF is a successful scan result, even when no bytes remain.

scanner.Scann(n) returns Result<io.ScanResult>. Its Bytes field is an i8[] containing only the bytes actually read, with no padding. Its End field is true when EOF prevented the scanner from filling the request. Asking for zero bytes succeeds without consuming input; a negative count panics. This differs from File.Readn(n), whose returned array always has length n and zero-fills unused positions.

HasNext(), HasNextln(), and HasNextc(delimiter) return Result<bool> without waiting for more input. They inspect buffered data and the operating system’s current readiness state. A successful true means a complete segment is available, or EOF has left remaining data to consume. A readiness failure is an error result, not false. Readiness is only a snapshot: another reader can consume input before the next scan.

Input scanning and files reference
FileModeAccess and creation behavior
Read / BinaryRead an existing file; no writing. Binary selects the binary form.
Write / BinaryWriteWrite a file, creating it if needed and truncating an existing file.
ReadWrite / BinaryReadWriteRead and write; create the file if needed without truncating existing contents.
Append / BinaryAppendWrite at the end of the file, creating it if needed.
ReadAppend / BinaryReadAppendRead the file and append writes at the end, creating it if needed.
Ocean
package main;
import "io";
import "os";

func main() {
    file := os.Open("input.txt", os.FileMode.Read).unwrap();
    scanner := io.NewScanner(file);
    line := scanner.Scanln().unwrap();
    io.Println(line).unwrap();
    file.Close();
}

The example opens input.txt for reading, consumes one line without its newline, prints that line, and closes the shared file handle. Each .unwrap() turns a recoverable I/O error into a panic for this small example. In application code, inspect the returned Result when an error should be handled without stopping the operation.

Byte reads, binary files, and file positions#

A file’s position is the byte offset used by its next read or write. Copies of an os.File share that position. Read(), Readn(n), and Readend() advance it as they consume bytes. Readall() instead reads the whole file and attempts to restore the previous position and EOF state, including after a read failure. If restoration fails, it returns an error and discards buffered scanner state. Setpos(position) also discards scanner buffers so later scans do not use bytes from the old position.

End-of-file and a failed read are different outcomes. For example, Read() returns a successful -1 at EOF, whereas a closed file, missing read permission, or native I/O failure returns an error Result. Calling Read() again after EOF has already been reported panics. A negative requested byte count also panics. Check the success or EOF indicator documented for the particular operation rather than treating every empty result as an error.

A failed operation may already have consumed input or written part of its output; failure does not promise that the file position and contents are unchanged. If a native close fails, the library does not retry it because the operating system may already have released the handle.

File.IsOpen(), CanRead(), CanWrite(), and IsBinary() return booleans describing the shared file state. os.FromDescriptor(fd, readable, writable) adopts a native descriptor as a text stream; a negative descriptor panics. File.NativeHandle() returns the native handle and panics when the file is closed. Keep one scanner per stream and avoid interleaving its buffered operations with direct reads or writes.

The printing functions io.Print, Println, Printf, and Printfln return Result<int>. A successful result contains the number of bytes written, including the newline for the newline-producing functions. Native output failures return errors; Unix output retries interrupted writes. io.Sprintf returns Result<string> and reports a mismatch between placeholders and arguments. io.Sprint returns a plain string. These conversion and formatting functions support the full unsigned integer ranges, including the u64 maximum 18446744073709551615.

File.SeekVersion() int exposes the scanner invalidation counter and panics for a closed file. A successful Setpos increments it; failure to restore a Readall cursor also increments it. Normal reads do not increment it. This counter is intended for buffered-reader coordination.

Byte reads, binary files, and file positions reference
File methodReturn value and behavior
Read()Result<int>: unsigned byte 0–255, or -1 at EOF
Readn(n)Result<os.ReadResult>: Bytes is an array<i8> with exactly n elements; End is true if EOF prevents filling it. Unread positions contain zeroes.
Readend()Result<array<i8>>: bytes from the current position through EOF; leaves the file positioned at EOF.
Readall()Result<array<i8>>: all file bytes; attempts to restore the original position and EOF state before returning.
Readchunk(n)Result<i8[]>: at most n bytes, with no zero padding; a successful empty array means no bytes remain at EOF.
Size()Result<int>: size in bytes, requires a seekable file
PollRead()Result<int>: OS readiness information without blocking
Write(text)Result<int>: number of bytes written
Close()Closes the shared file; repeated close succeeds; native failure panics
Setpos(position)Sets the position for the next operation. Valid offsets run from zero through the file size, including EOF; an invalid offset or native failure panics.
Ocean
file := os.Open("data.bin", os.FileMode.Binary).unwrap();
read := file.Readn(16).unwrap();
bytes := read.Bytes;
shortRead := read.End;
file.Setpos(0);
wholeFile := file.Readall().unwrap();
file.Close();

If the file contains fewer than sixteen remaining bytes, read.End is true and read.Bytes still has sixteen elements, with zeroes in the unread positions. Setpos(0) then returns to the beginning. Readall() reads the whole file while restoring that position, and Close() releases the shared handle.