os
Read process arguments, exit the process, access standard streams, and work with native files.
os.Exit#
Exit(code int) immediately terminates the entire program, including every native thread, with the supplied exit code. It never returns. Deferred calls, thread joins, and process cleanup do not run, and buffered output is not flushed automatically.
The value is explicitly converted from Ocean’s 64-bit int to the native C int. Exit-code interpretation follows the operating system; for example, POSIX shells normally observe the low eight bits. Use threads.Return() to end only the calling thread, or return normally from main to wait for workers before cleanup.
package main;
import "os";
func main() {
os.Exit(1);
}
os.Args#
Args() returns array<string>, an independently copied sized-array value. The compiler supplies process arguments through the library’s internal initialization hook.
The returned collection contains the process argument strings in their original order, including the executable name at index zero. User-supplied arguments follow it. Because it is an independent copy, modifying your local collection does not change the arguments retained by the package.
The example prints indices as well as values so the order is visible. For a command-line program, check the collection’s length before reading a required position. Alternatively, use checked two-binding indexing when an absent argument should be handled as a normal input error.
package main;
import "io";
import "os";
func main() {
args := os.Args();
for (index, argument := range args) {
io.Printfln("{}: {}", index, argument);
}
}
When using ocean run, the executable name refers to the temporary program Ocean created. It may differ from a separately built executable’s name. Use the arguments after index zero as application input instead of relying on that generated path.
Pass arguments#
With ocean run, normal arguments after the package location are passed to the generated executable. Ocean still recognizes its own options until a -- separator. Put -- before an argument such as --static or -o when that exact text should be passed to your program. A directly built executable receives arguments from the shell in the usual way.
The separator belongs to the compiler invocation; it is not itself a user argument passed to the application. Arguments following it are forwarded in order. For a built executable, the shell passes its argument list directly without involving the Ocean compiler.
Shell quoting still applies before the program receives those strings. For example, quoting "hello ocean" passes one argument containing a space, while writing hello ocean passes two arguments. Ocean does not re-split the strings returned by os.Args.
ocean run . hello ocean
ocean run subdir arg1 arg2
ocean build . -o app
./app hello ocean
The first ocean run command and the final ./app command both pass hello and ocean as two user arguments. The separate subdir example instead selects a package in that directory and supplies arg1 and arg2. The executable name at the beginning of the result can differ between them, especially because run uses a temporary output file.
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.
| FileMode | Access and creation behavior |
|---|---|
Read / Binary | Read an existing file; no writing. Binary selects the binary form. |
Write / BinaryWrite | Write a file, creating it if needed and truncating an existing file. |
ReadWrite / BinaryReadWrite | Read and write; create the file if needed without truncating existing contents. |
Append / BinaryAppend | Write at the end of the file, creating it if needed. |
ReadAppend / BinaryReadAppend | Read the file and append writes at the end, creating it if needed. |
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.
| File method | Return 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. |
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.