Skip to content

os #

Description

os provides common OS/platform independent functions for accessing command line arguments, reading/writing files, listing folders, handling processes etc.

See Named pipes for client/server FIFO endpoints.

On Windows, os.data_dir() uses %LocalAppData% for user-specific application data.

os.user_os() returns wasm32_emscripten when compiled for Emscripten.

On Windows, os.environ() walks UTF-16 environment entries without losing non-ASCII names or values. If the operating system cannot provide an environment block, it returns an empty map.

Console input

On Windows, os.input() supports both console and redirected standard input. It returns an empty string when the standard input handle is invalid.

Memory-mapped files

See memory-mapped files for file mappings and safe use of their byte views.

Path helpers

Windows short-path expansion counts output capacity in UTF-16 characters and reports an insufficient output buffer as an error.

os.executable() returns the process executable path. On Linux, NetBSD, and DragonFly, it uses the exact byte count returned by readlink, without requiring a NUL terminator.

os.base() removes all trailing separators before returning the final path element. For example, os.base('a///') returns a. An empty path returns ., and a path made entirely of separators returns one separator (/ for ///, or \ for \\).

is_abs_path follows the host operating system's path conventions. On Unix, a leading / identifies an absolute path. On Windows, it accepts drive-rooted paths (C:/x), UNC paths containing a server and share (//Host/share), and paths rooted on the current drive (/x or \x). The last form depends on the current drive; this predicate does not promise that the path names a drive. A bare doubled separator (// or \\) is an incomplete UNC path and returns false. Both slash styles, including mixed separators, are accepted on Windows.

This preserves V's rooted-path convention; it differs from Go's filepath.IsAbs, which requires a fully qualified Windows path.

os.join_path() and os.join_path_single() ignore empty elements and collapse repeated separators between elements. For example, joining a with /b gives a/b on POSIX or a\b on Windows. An absolute first nonempty element keeps its root: joining '' with /b gives /b on POSIX or \b on Windows. Windows UNC and device prefixes keep their initial double separator. A relative first element such as ./b still gives b when the base is empty. A component containing only the current directory, such as ./ or ././, remains . instead of an empty path.

os.dir() returns everything before the last separator, matching the classic dirname behaviour. It is not a "go up one level" primitive: on Windows it answers . for C: and the bare volume C: for C:\dir, and both of those name a current directory rather than a location in the given path.

os.dir(), os.base(), os.file_name() and os.split_path() agree on what a separator is. / always is one. \ is one on Windows, so a path may mix both there: os.file_name(r'a/b\c') is c. On other systems \ is a valid file name character, so the same call gives b\c; it separates only in a path that has no / at all, which keeps a Windows style path such as a\b\c.v usable everywhere.

os.parent_dir() is the walking variant. Every value it returns is safe to probe directly, and it returns an empty string once there is no parent left:

mut dir := os.dir(os.real_path(some_file))
for dir != '' {
    if os.is_file(os.join_path_single(dir, 'v.mod')) {
        break
    }
    dir = os.parent_dir(dir)
}

It differs from os.dir() in three ways:

  • A filesystem root has no parent, so /, C:\, C:, \\server\share and \\?\UNC\server\share all give '' and end the loop above.
  • The parent of a top level entry is the absolute root, so os.parent_dir(r'C:\dir') is C:\, never the drive relative C:.
  • A single element with no directory in it has no parent, so file.v gives ''.
  • A Windows drive relative path (C:, C:file.v, C:dir\file.v) gives '' as well, however many components it has. It resolves against the current directory of that drive, which is state the caller cannot see, and so does every one of its ancestors, so none of them is safe to hand back.

Each step is guaranteed to make progress: trailing separators name the same directory, so they are ignored, and os.parent_dir('/a/b/') is /a rather than /a/b. A separator is any byte the platform accepts as one, so a Windows path may mix / and \ and the last separator of either kind decides the parent.

os.path_rel() goes the other way: given a base and a target, it returns the path that leads from one to the other. It is the function to reach for instead of stripping a common prefix by hand, which gets the number of .. wrong as soon as the two paths share no prefix at all:

css := os.path_rel('/srv/app', '/srv/app/static/main.css') or { panic(err) } // 'static/main.css'
up := os.path_rel('/srv/app/logs', '/srv/app/static') or { panic(err) }      // '../static'

Both paths are normalized first, so . comes back for two spellings of the same path, and .. is collapsed before anything is compared. The separator in the result is the platform's, so on Windows the results above are static\main.css and ..\static. Two cases have no answer and return an error rather than a misleading path: when one path is absolute and the other is not, and when, after the leading components it shares with the target, the base still contains .. (the base climbs higher above the starting directory than the target does). A .. in the target is fine, so os.path_rel('a', '../b') is ../../b, and so is a .. the two paths share: os.path_rel('../a', '../b') is ../b.

os.path_rel() is purely lexical: it does not access the filesystem, resolve symlinks or use the working directory, so a/link/.. collapses to a even if link is a symlink. Pass the paths through os.real_path() or os.abs_path() first if that matters (this is also why mixing an absolute and a relative path is an error).

On Windows the two paths must also be on the same volume, since C:\a cannot be reached from D:\b by changing directory.

On Windows, os.uname() leaves release and version empty if the ver command fails or does not report a numeric version. Localized version labels are accepted.

Walking a tree

os.utime(path, actime, modtime) changes access and modification times for files and directories using Unix timestamps in seconds. On Windows, it accepts Unicode paths and reports Win32 error codes. Timestamps must use positive FILETIME tick counts below 2^63. The zero value (1601-01-01 00:00:00 UTC) is rejected because Windows treats it as "leave unchanged".

On Windows, os.stat() reports pre-1970 file and directory timestamps as negative Unix timestamps, including when the path reaches the target through a symbolic link.

On Windows, os.rm() clears a file's read-only attribute for deletion while preserving its other attributes. If removal fails, it attempts to restore the original attributes and reports the removal error. os.rmdir_all() continues after deletion errors and returns the first failure's message and code.

os.walk() reports files only, and os.walk_with_context() reports directories too but cannot skip them, so neither lets you say "do not descend into this one", and a large tree has to be read in full. os.walk_dir() reports every entry, directories included, and lets the callback prune:

os.walk_dir('/srv/app', fn (path string, entry os.WalkDirEntry) os.WalkDirAction {
    if err := entry.err {
        eprintln('skipping ${path}: ${err}')
        return .proceed
    }
    if entry.is_dir && entry.name in ['.git', 'node_modules', 'target'] {
        return .skip_dir // the directory is reported, its contents are never read
    }
    if !entry.is_dir && entry.name.ends_with('.v') {
        println(path)
    }
    return .proceed
}) or { panic(err) }

Returning .stop ends the walk where it stands. Entries are visited in lexical order and the root is reported first. Symlinks are reported but never followed, a symlinked root included; pass os.real_path(root) to walk what it points to.

entry.err is set in two cases. An entry that cannot be stat'ed, such as a missing root, arrives with is_dir left false, so a callback cannot accidentally descend into something unreadable. A directory that cannot be listed is reported a second time, with entry.err set and is_dir still true; returning .stop from that report ends the walk, anything else moves on to its next sibling.

To accumulate state across calls, pass a method of a mut local, as in os.walk_dir(root, c.visit), or capture a reference (mut c := &Counter{}): a closure that captures [mut n] only updates its own copy, see Closures.

Only os.walk_dir() and os.glob() sort. os.ls() returns the entries of a directory in the order the operating system reports them, and os.walk(), os.walk_ext() and os.walk_with_context() visit each directory in that order. It differs between platforms and filesystems: NTFS usually lists names alphabetically without regard to case, while on APFS or ext4 the order looks arbitrary. Sort the result when a stable order is needed:

import os

mut entries := os.ls('.')!
entries.sort()
println(entries)

Running commands

Use os.exec(['program', 'arg 1', 'arg 2']) when the command and its arguments are separate values. It runs the program directly without invoking a shell, so spaces and shell metacharacters inside arguments are passed literally. Pass raw arguments without os.quoted_path() or shell escaping.

os.exec_opt(args) returns an error on failure. os.exec_or_panic(args) and os.exec_or_exit(args) report failures by panicking or exiting. Use os.system_args(args) to inherit standard streams and return only the exit code. os.util.exec_with_timeout(args, milliseconds) returns none when the timeout elapses; it does not terminate the child process.

For configuration values such as a tool name followed by options, os.split_args(text)! parses quoting into literal arguments without shell expansion. Keep data such as paths and URLs as separate array elements rather than interpolating it into the configuration string.

The string APIs os.execute, os.raw_execute, os.system, os.execute_opt, os.execute_or_panic, os.execute_or_exit, and os.util.execute_with_timeout are deprecated because command strings can allow shell injection. Streaming shell commands through os.start_new_command or os.Command.start is also deprecated; use os.start_new_command_args(args) instead. It returns a CommandArgs stream with read_line(), eof, close(), and exit_code. read_line() waits for a complete line or the end of the output pipe, including when the child pauses between writes. For more control, use os.new_process(program) and process.set_args(args). These arguments are literal on Windows too: %PATH% stays %PATH%, and quotes and trailing backslashes are preserved. Expand environment variables explicitly with os.getenv() when that is intended.

Call process.wait() before process.close(), including after process.signal_kill(). On POSIX systems, waiting reaps the killed child and records its signal exit status. Repeated waits preserve the exit status already collected by wait() or is_alive().

On Windows, Result.exit_code and Process.code interpret the child's 32-bit exit status as a signed value: 0x80000000 becomes -2147483648 and 0xFFFFFFFF becomes -1. Check Process.status to distinguish a completed child returning -1 from a process that has not exited. On POSIX systems, normal exit codes range from 0 to 255.

When shell syntax is required, invoke the shell explicitly with an argument array. A shell still interprets its script as code: use a fixed script with positional arguments for data, and never interpolate untrusted values into the script. On Windows, shell builtins and batch scripts likewise require an explicit shell. For example, os.exec(['cmd', '/d', '/c', 'echo', 'hello']) runs the echo builtin.


Error codes

The IError returned by the failing os.* functions carries a message produced by the platform's strerror()/FormatMessage(), so the message text is not the same on every system. Check the error with a predicate instead:

import os

path := 'no_such_file.txt'
if st := os.stat(path) {
    println('${path} has ${st.size} bytes')
} else {
    if os.is_not_exist(err) {
        println('${path} does not exist')
    }
}

os.is_not_exist, os.is_exist and os.is_permission_denied accept every code the platform may use for that condition. Checking the error is also what avoids the extra os.exists() call that would otherwise be a time-of-check/time-of-use race.

On POSIX systems, the os.* functions report a C errno value. On Windows, the functions built on the C runtime (for example os.stat, os.rm, os.read_file, os.open, os.create, os.write_file, os.chdir, os.truncate and os.rename) report a C errno value too, while the ones built on the Win32 API (os.mkdir, os.rmdir, os.ls, os.symlink and os.link) report a Win32 error code. The os.error_code_* constants hold one of these codes for a condition, so prefer the predicates over comparing err.code() with them.

os.utime, os.symlink and os.link preserve the Windows API's error code when they fail, so duplicate targets and missing paths can be classified with these predicates. os.hostname and os.loginname also preserve their Win32 error codes on failure.


A few os module functions can lead to the TOCTOU vulnerability if used incorrectly. TOCTOU (Time-of-Check-to-Time-of-Use problem) can occur when a file, folder or similar is checked for certain specifications (e.g. read, write permissions) and a change is made afterwards. In the time between the initial check and the edit, an attacker can then cause damage. The following example shows an attack strategy on the left and an improved variant on the right so that TOCTOU is no longer possible.

Example
Hint: os.create() opens a file in write-only mode

Possibility for TOCTOU attack TOCTOU not possible
if os.is_writable("file") {
    // time to make a quick attack
    // (e.g. symlink /etc/passwd to `file`)

    mut f := os.create('path/to/file')!
    // do something with file
    f.close()
}
mut f := os.create('path/to/file') or {
    println("file not writable")
}

// file is locked
// do something with file

f.close()

Proven affected functions
The following functions should be used with care and only when used correctly.

  • os.is_readable()
  • os.is_writable()
  • os.is_executable()
  • os.is_link()

get_line() removes CRLF and LF line endings from standard input on every platform.

Windows process exit codes and disk usage use the SDK's DWORD and ULARGE_INTEGER output types. These bindings keep Clang's incompatible pointer diagnostics enabled.

On Windows, exec and Process accept an absolute executable path without an extension. They use that exact file when it exists, then try the same path with .exe appended. Explicit extensions are preserved.

On Windows, os.get_error_msg removes the trailing CR/LF line break from system messages. Error text returned by operations using it retains the message's punctuation.

Child process output

On Windows, os.exec() captures bytes from successful child-pipe reads only. Closing the output pipe does not append a previous chunk again. Commands with no output return an empty output string.

Writing arrays

os.write_file_array() closes its file even when writing fails, including when a device is full or a pipe reader closes. The write error is still returned to the caller.

os.cp reports source read failures as cp: failed to read from <source> and closes both files.

File identity and user directories

is_absolute requires a drive root or UNC volume on Windows. Drive-relative paths such as C:file and paths rooted on the current drive such as /file return false. volume_name returns the drive or UNC root on Windows and an empty string elsewhere.

same_file(a, b) follows symbolic links and compares filesystem object identity. It supports Unicode paths and directories on Windows; missing or inaccessible paths return an error. copy_file(src, dst) follows source links, copies contents and basic permission bits (0o777), and reports read, write, or permission-setting errors. Copying to the source or a hard link to it is rejected.

user_home_dir uses a nonempty HOME on POSIX or USERPROFILE on Windows, where HOMEDRIVE plus HOMEPATH is a fallback. user_cache_dir and user_config_dir use LOCALAPPDATA and APPDATA on Windows, falling back to AppData/Local and AppData/Roaming. On POSIX they use nonempty, absolute XDG_CACHE_HOME and XDG_CONFIG_HOME; empty values fall back to ~/.cache and ~/.config. Variables from the other platform are ignored.

Constants #

const error_code_noent = $if windows { 2 } $else { int(C.ENOENT) }

error_code_noent is the code for a path that does not exist. It is ENOENT on POSIX and ERROR_FILE_NOT_FOUND on Windows, which have the same value there. Win32 functions report ERROR_PATH_NOT_FOUND instead for a missing directory earlier in the path, which is_not_exist also accepts.

const error_code_denied = $if windows { 5 } $else { int(C.EACCES) }

error_code_denied is the code for a permission failure. It is EACCES on POSIX and ERROR_ACCESS_DENIED on Windows.

const error_code_perm = $if windows { 5 } $else { int(C.EPERM) }

error_code_perm is the code for an operation the caller is not allowed to perform. It is EPERM on POSIX. Windows has no separate code for it and uses ERROR_ACCESS_DENIED, so it is equal to error_code_denied there.

const error_code_exist = $if windows { 183 } $else { int(C.EEXIST) }

error_code_exist is the code for a path that already exists. It is EEXIST on POSIX and ERROR_ALREADY_EXISTS on Windows.

const error_code_notdir = $if windows { 267 } $else { int(C.ENOTDIR) }

error_code_notdir is the code for a directory operation that targeted a file. It is ENOTDIR on POSIX and ERROR_DIRECTORY on Windows.

Available on Windows only.

const hkey_local_machine = voidptr(0x80000002)
const hkey_current_user = voidptr(0x80000001)
const key_query_value = 0x0001
const key_set_value = 0x0002
const key_enumerate_sub_keys = 0x0008
const key_wow64_32key = 0x0200

Windows Registry Constants

Available on Windows only.

const hwnd_broadcast = voidptr(0xFFFF)
const wm_settingchange = 0x001A
const smto_abortifhung = 0x0002

Windows Messages

@[markused]
const args = arguments()
const error_code_not_set = int(-1)

Magic constant because zero is used explicitly at times

const max_path_len = 4096
const wd_at_startup = getwd()

Available on macOS only.

const sys_write = 4
const sys_open = 5
const sys_close = 6
const sys_mkdir = 136
const sys_creat = 8
const sys_open_nocancel = 398
const sys_stat64 = 338

Available on Linux only.

const sys_write = 1
const sys_open = 2
const sys_close = 3
const sys_mkdir = 83
const sys_creat = 85

Available on Unix only.

const path_separator = '/'

path_separator is the platform specific separator string, used between the folders and filenames in a path. It is '/' on POSIX, and '\' on Windows.

Available on Unix only.

const path_delimiter = ':'

path_delimiter is the platform specific delimiter string, used between the paths in environment variables like PATH. It is ':' on POSIX, and ';' on Windows.

Available on Unix only.

const path_devnull = '/dev/null'

path_devnull is a platform-specific file path of the null device. It is '/dev/null' on POSIX, and r'\.\nul' on Windows.

Available on Unix only.

const s_ifmt = u32(0xF000) // type of file
const s_ifdir = u32(0x4000) // directory
const s_ifreg = u32(0x8000) // regular file
const s_iflnk = u32(0xa000) // link
const s_isuid = u32(0o4000) // SUID
const s_isgid = u32(0o2000) // SGID
const s_isvtx = u32(0o1000) // Sticky
const s_irusr = u32(0o0400) // Read by owner
const s_iwusr = u32(0o0200) // Write by owner
const s_ixusr = u32(0o0100) // Execute by owner
const s_irgrp = u32(0o0040) // Read by group
const s_iwgrp = u32(0o0020) // Write by group
const s_ixgrp = u32(0o0010) // Execute by group
const s_iroth = u32(0o0004) // Read by others
const s_iwoth = u32(0o0002) // Write by others
const s_ixoth = u32(0o0001)

(Must be realized in Syscall) (Must be specified) ref: http://www.ccfit.nsu.ru/~deviv/courses/unix/unix/ng7c229.html

Available on Windows only.

const path_separator = '\\'

path_separator is the platform specific separator string, used between the folders, and filenames in a path. It is '/' on POSIX, and '\' on Windows.

Available on Windows only.

const path_delimiter = ';'

path_delimiter is the platform specific delimiter string, used between the paths in environment variables like PATH. It is ':' on POSIX, and ';' on Windows.

Available on Windows only.

const path_devnull = r'\\.\nul'

path_devnull is a platform-specific file path of the null device. It is '/dev/null' on POSIX, and r'\.\nul' on Windows.

fn abs_path #

fn abs_path(path string) string

abs_path joins the current working directory with the given path (if the path is relative), and returns the absolute path representation.

fn add_vectored_exception_handler #

Available on Windows only.

fn add_vectored_exception_handler(first bool, handler VectoredExceptionHandler)

This is defined in builtin because we use vectored exception handling for our unhandled exception handler on windows As a result this definition is commented out to prevent duplicate definitions from displeasing the compiler fn C.AddVectoredExceptionHandler(u32, VectoredExceptionHandler)

fn args_after #

fn args_after(cut_word string) []string

args_after returns all os.args, located after a specified cut_word. When cut_word is NOT found, os.args is returned unmodified.

fn args_before #

fn args_before(cut_word string) []string

args_before returns all os.args, located before a specified cut_word. When cut_word is NOT found, os.args is returned unmodified.

fn base #

fn base(path string) string

base returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, base returns ".". If the path consists entirely of separators, base returns a single separator. On Windows both / and \ separate path elements. On other systems \ does so only in a path that has no /.

fn cache_dir #

fn cache_dir() string

cache_dir returns the path to a writable user-specific folder, suitable for writing non-essential data. See: https://specifications.freedesktop.org/basedir-spec/latest/ . There is a single base directory relative to which user-specific non-essential (cached) data should be written. This directory is defined by the environment variable $XDG_CACHE_HOME. $XDG_CACHE_HOME defines the base directory relative to which user specific non-essential data files should be stored. If $XDG_CACHE_HOME is either not set or empty, a default equal to $HOME/.cache should be used.

Note: This function ensures that the returned directory exists and panics if directory creation fails.

fn chdir #

fn chdir(path string) !

chdir changes the current working directory to the new directory in path.

fn chmod #

fn chmod(path string, mode int) !

chmod change file access attributes of path to mode. Octals like 0o600 can be used.

fn chown #

fn chown(path string, owner int, group int) !

chown changes the owner and group attributes of path to owner and group.

fn config_dir #

fn config_dir() !string

config_dir returns the path to the user configuration directory (depending on the platform). On Windows, that is %AppData%. On macOS, that is ~/Library/Application Support. On the rest, that is $XDG_CONFIG_HOME, or if that is not available, ~/.config. If the path cannot be determined, it returns an error. (for example, when $HOME on Linux, or %AppData% on Windows is not defined)

fn copy_file #

fn copy_file(src string, dst string) !

copy_file copies src's contents and basic permission bits (0o777) to dst, following links. It rejects destinations that refer to the source object. Read, write and permission-setting failures return an error.

fn cp #

fn cp(src string, dst string, config CopyParams) !

cp copies the file src to the file or directory dst. If dst specifies a directory, the file will be copied into dst using the base filename from src. If dst specifies a file that already exists, it will be replaced by default. Can be overridden to fail by setting fail_if_exists: true

fn cp_all #

fn cp_all(src string, dst string, overwrite bool) !

cp_all will recursively copy src to dst, optionally overwriting files or dirs in dst.

fn create #

@[noinline]
fn create(path string) !File

create creates or opens a file at a specified location and returns a write-only File object.

fn data_dir #

fn data_dir() string

data_dir returns the path to a writable user-specific folder, suitable for writing application data. On Windows, that is %LocalAppData%, or if that is not available, %USERPROFILE%/AppData/Local. On the rest, that is $XDG_DATA_HOME, or if that is not available, $HOME/.local/share.

Note: This function ensures that the returned directory exists and panics if directory creation fails.

fn debugger_present #

fn debugger_present() bool

debugger_present returns a bool indicating if the process is being debugged.

fn dir #

fn dir(path string) string

dir returns all but the last element of path, typically the path's directory. After dropping the final element, trailing slashes are removed. If the path is empty, dir returns ".". If the path consists entirely of separators, dir returns a single separator. The returned path does not end in a separator unless it is the root directory. On Windows both / and \ separate path elements. On other systems \ does so only in a path that has no /.

fn disk_usage #

@[manualfree]
fn disk_usage(path string) !DiskUsage

disk_usage returns disk usage of path.

fn ensure_folder_is_writable #

@[manualfree]
fn ensure_folder_is_writable(folder string) !

ensure_folder_is_writable checks that folder exists, and is writable to the process by creating an empty file in it, then deleting it.

fn environ #

fn environ() map[string]string

environ returns a map of all the current environment variables. See: https://linux.die.net/man/5/environ for Unix platforms. See: https://docs.microsoft.com/bg-bg/windows/win32/api/processenv/nf-processenv-getenvironmentstrings for Windows OS.

fn error_posix #

@[inline; manualfree]
fn error_posix(e SystemError) IError

error_posix returns a POSIX error: Code defaults to last error (from C.errno) Message defaults to POSIX error message for the error code

fn error_win32 #

@[inline; manualfree]
fn error_win32(e SystemError) IError

error_win32 returns a Win32 API error: example:

   // save error code immediately, or it will be overwritten by other API
   // function calls, even by `str_intp`.
   code := int(C.GetLastError())
   error_win32(
      msg : 'some error'
      code : code
   )

wrong usage:

   error_win32(
       msg : 'some error ${path}'		// this will overwrite error code
       code : int(C.GetLastError())
   )

Message defaults to Win 32 API error message for the error code

fn exec #

fn exec(args []string) Result

exec starts the specified command with arguments, waits for it to complete, and returns its output.

fn exec_opt #

fn exec_opt(args []string) !Result

exec_opt returns the os.Result of executing args, or an error with its output on failure.

fn exec_or_exit #

fn exec_or_exit(args []string) Result

exec_or_exit returns the os.Result of executing args, or exit with its output on failure.

fn exec_or_panic #

fn exec_or_panic(args []string) Result

exec_or_panic returns the os.Result of executing args, or panic with its output on failure.

fn executable #

@[manualfree]
fn executable() string

executable returns the path name of the executable that started the current process.

fn execute #

@[deprecated: 'use os.exec with an argument array; command strings can allow shell injection']
fn execute(cmd string) Result

execute starts the specified command, waits for it to complete, and returns its output.

fn execute_opt #

@[deprecated: 'use os.exec_opt with an argument array; command strings can allow shell injection']
fn execute_opt(cmd string) !Result

execute_opt returns the os.Result of executing cmd, or an error with its output on failure.

fn execute_or_exit #

@[deprecated: 'use os.exec_or_exit with an argument array; command strings can allow shell injection']
fn execute_or_exit(cmd string) Result

execute_or_exit returns the os.Result of executing cmd, or exit with its output on failure.

fn execute_or_panic #

@[deprecated: 'use os.exec_or_panic with an argument array; command strings can allow shell injection']
fn execute_or_panic(cmd string) Result

execute_or_panic returns the os.Result of executing cmd, or panic with its output on failure.

fn execve #

fn execve(cmdpath string, cmdargs []string, envs []string) !

execve - loads and executes a new child process, in place of the current process. The child process executable is located in cmdpath. The arguments, that will be passed to it are in args. You can pass environment variables to through envs.

Note: this function will NOT return when successful, since the child process will take control over execution.

fn execvp #

fn execvp(cmdpath string, cmdargs []string) !

execvp - loads and executes a new child process, in place of the current process. The child process executable is located in cmdpath. The arguments, that will be passed to it are in args.

Note: this function will NOT return when successful, since the child process will take control over execution.

fn existing_path #

fn existing_path(path string) !string

existing_path returns the existing part of the given path. An error is returned if there is no existing part of the given path.

fn exists #

fn exists(path string) bool

exists returns true if path (file or directory) exists.

Note that when used on symlinks, if the target of the symlink does not exist, the behavior of this function is complex. On linux, mac, and similar systems, on such a symlink, this function returns false. (This may make sense, in the sense that such a path does not contain anything readable. It is also the same as the libc 'access' function, and may be familiar from that regard. On the other hand, this case may be surprising, since it means this function can return "false" for a path that exists enough that trying to create a new file or dir there subsequently (even aside from TOCTOU issues) will fail with EEXIST.) On windows systems, a symlink with a target that does not exist, this function returns true. Consider using lstat() for a less ambiguous result about whether a path is occupied or not; whether lstat returns any result or a "not exists" error gives a clear indication of whether the path is occupied.

fn exists_in_system_path #

fn exists_in_system_path(prog string) bool

exists_in_system_path returns true if prog exists in the system's PATH.

fn expand_tilde_to_home #

fn expand_tilde_to_home(path string) string

expand_tilde_to_home expands the character ~ in path to the user's home directory. See also home_dir().

fn fd_close #

fn fd_close(fd int) int

fd_close closes the file descriptor. It returns 0 on success.

fn fd_dup #

fn fd_dup(fd int) int

fd_dup duplicates a file descriptor.

fn fd_dup2 #

fn fd_dup2(fd1 int, fd2 int) int

fd_dup2 duplicates file descriptor fd1 to descriptor number fd2 If fd2 is already open, it is closed first before being reused. Returns the new file descriptor on success, or -1 on error.

fn fd_is_pending #

fn fd_is_pending(fd int) bool

fd_is_pending returns true, when there is pending data, waiting to be read from file descriptor fd. If the file descriptor is closed, or if reading from it, will block (there is no data), fd_is_pending returns false.

fn fd_read #

fn fd_read(fd int, maxbytes int) (string, int)

fd_read reads data from the file descriptor. It returns the read data, and how many bytes were read. On signal interruption (EINTR), the read is retried so callers do not see spurious empty results when a signal (for example a Boehm GC stop-the-world signal in a multi-threaded program) interrupts a blocking read.

fn fd_slurp #

fn fd_slurp(fd int) []string

fd_slurp reads all the remaining data from the file descriptor.

fn fd_write #

fn fd_write(fd int, s string)

fd_write writes the given string to the file descriptor. It blocks until all the data in the string is written.

fn fifo_client #

fn fifo_client(path string) !&Fifo

fifo_client connects to the endpoint at path for writing (blocks until a server is waiting).

fn fifo_server #

fn fifo_server(path string, mode u32) !&Fifo

fifo_server creates the endpoint at path and blocks until a client connects, then returns it for reading. On POSIX path is a filesystem node (removed by the caller when done); on Windows it is used as the pipe name. mode is the POSIX permission bits (ignored on Windows).

fn file_ext #

fn file_ext(opath string) string

file_ext will return the part after the last occurrence of . in path. The . is included. Examples:

assert os.file_ext('file.v') == '.v'
assert os.file_ext('.ignore_me') == ''
assert os.file_ext('.') == ''

fn file_last_mod_unix #

fn file_last_mod_unix(path string) i64

file_last_mod_unix returns the "last modified" time stamp of file in path.

fn file_name #

fn file_name(path string) string

file_name will return all characters found after the last path separator. file extension is included. On Windows both / and \ separate path elements. On other systems \ does so only in a path that has no /.

fn file_size #

fn file_size(path string) u64

file_size returns the size in bytes, of the file located in path. If an error occurs it returns 0. Note that use of this on symbolic links on Windows returns always 0.

fn fileno #

fn fileno(cfile voidptr) int

fileno returns the file descriptor of an opened C file.

fn find_abs_path_of_executable #

fn find_abs_path_of_executable(exe_name string) !string

find_abs_path_of_executable searches the environment PATH for the absolute path of the given executable name.

fn flush #

fn flush()

flush will flush the stdout buffer.

fn fork #

fn fork() int

fork will fork the current system process and return the pid of the fork.

fn from_slash #

fn from_slash(path string) string

from_slash returns the result of replacing each slash (/) character is path with a separator character.

fn get_error_msg #

fn get_error_msg(code int) string

get_error_msg return error code representation in string.

fn get_file_handle #

Available on Windows only.

fn get_file_handle(path string) HANDLE

Ref - https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/get-osfhandle?view=vs-2019 get_file_handle retrieves the operating-system file handle that is associated with the specified file descriptor.

fn get_line #

fn get_line() string

get_line returns a one-line string from stdin, removing its CRLF or LF line ending.

fn get_lines #

fn get_lines() []string

get_lines returns an array of strings read from stdin. reading is stopped when an empty line is read.

fn get_lines_joined #

fn get_lines_joined() string

get_lines_joined returns a string of the values read from stdin. reading is stopped when an empty line is read.

fn get_module_filename #

Available on Windows only.

fn get_module_filename(handle HANDLE) !string

Ref - https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea get_module_filename retrieves the fully qualified path for the file that contains the specified module. The module must have been loaded by the current process.

fn get_raw_line #

@[manualfree]
fn get_raw_line() string

get_raw_line returns a one-line string from stdin along with \n if there is any.

fn get_raw_lines #

fn get_raw_lines() []string

get_raw_lines reads all input lines from stdin, as an array of strings.

Note: unlike os.get_lines, empty lines (that contain only \r\n or \n), will be present in the output. Reading is stopped, only on EOF of stdin.

fn get_raw_lines_joined #

fn get_raw_lines_joined() string

get_raw_lines_joined reads all input lines from stdin. It returns them as one large string. Note: unlike os.get_lines_joined, empty lines (that contain only \r\n or \n), will be present in the output. Reading is stopped, only on EOF of stdin.

fn get_raw_stdin #

fn get_raw_stdin() []u8

get_raw_stdin will get the raw input from stdin.

fn get_trimmed_lines #

fn get_trimmed_lines() []string

get_trimmed_lines reads all input lines from stdin, as an array of strings. The ending new line characters \r and \n, are removed from each line.

Note: unlike os.get_lines, empty lines will be present in the output as empty strings ''. Reading is stopped, only on EOF of stdin.

fn getegid #

@[inline]
fn getegid() int

getegid returns the effective group ID of the calling process.

fn getenv #

fn getenv(key string) string

getenv returns the value of the environment variable named by the key. If there is not one found, it returns an empty string ''.

fn getenv_opt #

@[manualfree]
fn getenv_opt(key string) ?string

getenv_opt returns the value of a given environment variable. Returns none if the environment variable does not exist.

fn geteuid #

@[inline]
fn geteuid() int

geteuid returns the effective user ID of the calling process.

fn getgid #

@[inline]
fn getgid() int

getgid returns the real group ID of the calling process.

fn getpid #

@[inline]
fn getpid() int

getpid returns the process ID (PID) of the calling process.

fn getppid #

@[inline]
fn getppid() int

getppid returns the process ID of the parent of the calling process.

fn getuid #

@[inline]
fn getuid() int

getuid returns the real user ID of the calling process.

fn getwd #

@[manualfree]
fn getwd() string

getwd returns the absolute path of the current directory.

fn glob #

@[manualfree]
fn glob(patterns ...string) ![]string

glob function searches for all the pathnames matching patterns and returns a sorted list of found pathnames. On Unix, each * matches zero or more characters within a path component; literal pieces between multiple stars must occur in order without overlapping.

fn home_dir #

fn home_dir() string

home_dir returns the path to the current user's home directory.

fn hostname #

fn hostname() !string

hostname returns the hostname (system's DNS name) or POSIX error message if the hostname call fails.

fn inode #

fn inode(path string) FileInfo

inode returns the metadata of the file/inode, containing inode type, permission information, size and modification time. It supports Windows for regular files, but it doesn't matter if you use owner, group or others when checking permissions on Windows. if a symlink is targeted, it returns info on the link, not the target.

fn input #

fn input(prompt string) string

input returns a one-line string from stdin, after printing a prompt. Returns <EOF> in case of an error (end of input).

fn input_opt #

fn input_opt(prompt string) ?string

input_opt returns a one-line string from stdin, after printing a prompt. Returns none in case of an error (end of input).

fn input_password #

fn input_password(prompt string) !string

input_password prompts the user for a password-like secret. It disables the terminal echo during user input and resets it back to normal when done.

fn is_abs_path #

fn is_abs_path(path string) bool

is_abs_path returns true if the given path is absolute. On Windows it also accepts paths rooted on the current drive, such as \x or /x; these do not specify a drive. UNC paths require a server and share, so a bare doubled separator (// or \\) returns false.

fn is_absolute #

fn is_absolute(path string) bool

is_absolute reports whether path is rooted at '/' on POSIX, or names a drive root or UNC volume on Windows. Windows drive-relative paths such as 'C:file' and paths rooted on the current drive such as '/file' are relative.

fn is_atty #

fn is_atty(fd int) int

is_atty returns 1 if the fd file descriptor is open and refers to a terminal.

fn is_dir #

fn is_dir(path string) bool

is_dir returns a bool indicating whether the given path is a directory.

fn is_dir_empty #

@[manualfree]
fn is_dir_empty(path string) bool

is_dir_empty will return a bool whether or not path is empty. Note that it will return true if path does not exist.

fn is_executable #

fn is_executable(path string) bool

is_executable returns true if path is executable. Warning: is_executable() is known to cause a TOCTOU vulnerability when used incorrectly (for more information: https://github.com/vlang/v/blob/master/vlib/os/README.md).

fn is_exist #

fn is_exist(err IError) bool

is_exist reports whether err was caused by a path that already exists.

fn is_file #

fn is_file(path string) bool

is_file returns a bool indicating whether the given path is a file.

fn is_main_thread #

fn is_main_thread() bool

is_main_thread returns whether the current thread is the main thread.

fn is_not_exist #

fn is_not_exist(err IError) bool

is_not_exist reports whether err was caused by a path that does not exist.

fn is_path_separator #

fn is_path_separator(c u8) bool

is_path_separator reports whether c separates path elements on this platform (both '/' and '\' on Windows, '/' elsewhere).

fn is_permission_denied #

fn is_permission_denied(err IError) bool

is_permission_denied reports whether err was caused by a permission failure. It accepts both EACCES and EPERM.

fn is_readable #

@[manualfree]
fn is_readable(path string) bool

is_readable returns true if path is readable. Warning: is_readable() is known to cause a TOCTOU vulnerability when used incorrectly (for more information: https://github.com/vlang/v/blob/master/vlib/os/README.md).

fn is_writable #

@[manualfree]
fn is_writable(path string) bool

is_writable returns true if path is writable. Warning: is_writable() is known to cause a TOCTOU vulnerability when used incorrectly (for more information: https://github.com/vlang/v/blob/master/vlib/os/README.md).

fn join_path #

@[manualfree]
fn join_path(base string, dirs ...string) string

join_path joins any number of path elements into a single path, separating them with a platform-specific path_separator. Empty elements are ignored. Windows platform output will rewrite forward slashes to backslash. An absolute first nonempty element retains its root when base is empty. A component naming only the current directory remains .. Consider looking at the unit tests in os_test.v for semi-formal API.

fn join_path_single #

@[manualfree]
fn join_path_single(base string, elem string) string

join_path_single appends the elem after base, separated with a platform-specific path_separator. Empty elements are ignored. An absolute elem retains its root when base is empty. An elem naming only the current directory remains ..

fn last_error #

@[manualfree]
fn last_error() IError

last_error returns a V error, formed by the last libc error (from GetLastError() on windows and from errno on !windows).

fn local_bin_dir #

fn local_bin_dir() string

local_bin_dir returns $HOME/.local/bin, which is guaranteed to be in the PATH of the current user. It is compatible with stributions, following the XDG spec from https://specifications.freedesktop.org/basedir-spec/latest/ :

User-specific executable files may be stored in $HOME/.local/bin.
Distributions should ensure this directory shows up in the UNIX $PATH environment variable, at an appropriate place.

Note: This function ensures that the returned directory exists and panics if directory creation fails.

fn log #

fn log(s string)

log will print "os.log: "+s ...

fn loginname #

fn loginname() !string

loginname returns the name of the user logged in on the controlling terminal of the process. It returns a POSIX error message, if the getlogin call fails.

fn ls #

@[manualfree]
fn ls(path string) ![]string

ls returns ![]string of the files and dirs in the given path ( os.ls uses C.readdir ). Symbolic links are returned to be files. For recursive list see os.walk functions. The entries come in the order the operating system reports them, which os.ls does not sort. That order differs between platforms and filesystems, so call .sort() on the result when a stable order is needed. See also: os.walk, os.walk_ext, os.is_dir, os.is_file

Example

  entries := os.ls(os.home_dir()) or { [] }
  for entry in entries {
    if os.is_dir(os.join_path(os.home_dir(), entry)) {
      println('dir: ${entry}')
    } else {
      println('file: ${entry}')
    }
  }

fn lstat #

fn lstat(path string) !Stat

lstat is similar to stat/1 for normal files/folders. Unlike stat/1, however, it will return the stat info for a symlink, instead of its target.

fn mkdir #

fn mkdir(path string, params MkdirParams) !

mkdir creates a new directory with the specified path.

fn mkdir_all #

fn mkdir_all(opath string, params MkdirParams) !

mkdir_all will create a valid full path of all directories given in path.

fn mmap_create #

fn mmap_create(path string, len u64) !&Mmap

mmap_create creates (or truncates) path to len bytes and maps it read-write, zero-filled. len must be positive.

fn mmap_open #

fn mmap_open(path string, mode MmapMode) !&Mmap

mmap_open maps the whole file at path. Missing and empty files are errors (use mmap_create for those).

fn mv #

fn mv(source string, target string, opts MvParams) !

mv moves files or folders from src to dst.

fn mv_by_cp #

fn mv_by_cp(source string, target string, opts MvParams) !

mv_by_cp copies files or folders from source to target. If copying is successful, source is deleted. It may be used when the paths are not on the same mount/partition.

fn new_process #

fn new_process(filename string) &Process

new_process - create a new process descriptor.

Note: new does NOT start the new process. That is done because you may want to customize it first, by calling different set_ methods on it. In order to start it, call p.run() or p.wait() The filename and arguments are used literally, without shell or environment expansion.

fn norm_path #

@[direct_array_access]
fn norm_path(path string) string

norm_path returns the normalized version of the given path by resolving backlinks (..), turning forward slashes into back slashes on a Windows system and eliminating:- references to current directories (.)

  • redundant path separators
  • the last path separator

fn open #

fn open(path string) !File

open tries to open a file from a given path for reading.

fn open_append #

fn open_append(path string) !File

open_append tries to open a file from a given path. If successful, it and returns a File for appending.

fn open_file #

@[noinline]
fn open_file(path string, mode string, options ...int) !File

open_file tries to open or create a file with custom flags and permissions.

fn open_uri #

fn open_uri(uri string) !

open_uri opens a given uri.

fn page_size #

fn page_size() int

page_size returns the page size in bytes.

fn parent_dir #

fn parent_dir(path string) string

parent_dir returns the parent directory of the given path, or an empty string when path has no parent. A path has no parent when it is a filesystem root (/, C:\, \\server\share, \\?\UNC\server\share), the current directory reference ., a single element with no directory in it (file.v), or a Windows drive relative path (C:, C:file.v, C:dir\file.v), which resolves against the current directory of that drive - state the caller cannot see, and which every one of its ancestors shares, so none of them is safe to hand back. A separator is any byte the platform accepts as one, so a Windows path may mix / and \ freely, and trailing separators are ignored: they name the same directory, so parent_dir('/a/b/') is /a, exactly like /a/b.

Every value parent_dir returns is safe to probe directly, and that is what separates it from dir, which has two Windows answers that resolve against a current directory rather than against the path they came from: dir('C:') is the relative ., and dir(r'C:\outside') is the bare volume C:, which names the current directory on drive C, not its root. parent_dir reports "no parent" for the first and the absolute root C:\ for the second, so a parent directory walk can neither escape the drive nor probe a drive relative path on the way up.

fn path_rel #

fn path_rel(basepath string, targpath string) !string

path_rel returns a path which, resolved against basepath, reaches targpath. It follows Go's path/filepath.Rel, except that the result is always normalized: both paths are normalized first, . is returned when they name the same path, and an error is returned when targpath cannot be expressed relative to basepath. That happens when one path is absolute and the other is not, when the two paths are on different Windows volumes, or when, after the leading components it shares with targpath, basepath still contains ... path_rel is purely lexical: it does not access the filesystem, resolve symlinks or use the working directory. Pass the paths through os.real_path or os.abs_path first if that matters.

Example

assert os.path_rel('/a/b', '/a/b/c')! == 'c'
assert os.path_rel('/a/b', '/a/c')! == os.join_path('..', 'c')

fn pipe #

fn pipe() !Pipe

pipe creates a new pipe for inter-process communication.

fn posix_get_error_msg #

fn posix_get_error_msg(code int) string

posix_get_error_msg returns error code representation in string.

fn posix_set_permission_bit #

fn posix_set_permission_bit(path_s string, mode u32, enable bool)

Turns the given bit on or off, depending on the enable parameter.

fn quoted_path #

fn quoted_path(path string) string

quoted path - return a quoted version of the path, depending on the platform.

fn raw_execute #

@[deprecated: 'use os.exec with an argument array; command strings can allow shell injection']
@[unsafe]
fn raw_execute(cmd string) Result

raw_execute does the same as execute on Unix platforms. On Windows raw_execute starts the specified command, waits for it to complete, and returns its output. It's marked as unsafe to help emphasize the problems that may arise by allowing, for example, user provided escape sequences.

fn read_apk_asset #

Available on Android only.

fn read_apk_asset(path string) ![]u8

read_apk_asset returns all the data located at path. path is expected to be relative to the APK/AAB assets directory.

fn read_bytes #

@[manualfree]
fn read_bytes(path string) ![]u8

read_bytes returns all bytes read from file in path.

fn read_file #

@[manualfree]
fn read_file(path string) !string

read_file reads the file in path and returns the contents.

fn read_file_array #

fn read_file_array[T](path string) []T

read_file_array reads an array of T values from file path.

fn read_lines #

@[manualfree]
fn read_lines(path string) ![]string

read_lines reads the file in path into an array of lines.

fn real_path #

@[manualfree]
fn real_path(fpath string) string

real_path returns the full absolute path for fpath, with all relative ../../, symlinks and so on resolved. See http://pubs.opengroup.org/onlinepubs/9699919799/functions/realpath.html Also https://insanecoding.blogspot.com/2007/11/pathmax-simply-isnt.html and https://insanecoding.blogspot.com/2007/11/implementing-realpath-in-c.html On Windows, extended-length path prefixes like \\?\ and \\?\UNC\ are normalized back to standard DOS and UNC paths.

Note: this particular rabbit hole is deep ...

fn rename #

fn rename(src string, dst string) !

rename renames the file or folder from src to dst. Use mv to move or rename a file in a platform independent manner.

fn rename_dir #

fn rename_dir(src string, dst string) !

rename_dir renames the folder from src to dst. Use mv to move or rename a file in a platform independent manner.

fn resource_abs_path #

@[manualfree]
fn resource_abs_path(path string) string

resource_abs_path returns an absolute path, for the given path. (the path is expected to be relative to the executable program) See https://discordapp.com/channels/592103645835821068/592294828432424960/630806741373943808 It gives a convenient way to access program resources like images, fonts, sounds and so on, no matter how the program was started, and what is the current working directory.

fn rm #

fn rm(path string) !

rm removes file in path. On Windows it clears the file's read-only attribute for deletion and preserves its other attributes. If deletion fails, it attempts to restore the original attributes.

fn rmdir #

fn rmdir(path string) !

rmdir removes a specified directory.

fn rmdir_all #

fn rmdir_all(path string) !

rmdir_all recursively removes the specified directory. It continues after deletion errors and returns the first error's message and code.

fn same_file #

fn same_file(a string, b string) !bool

same_file reports whether a and b refer to the same filesystem object, following symbolic links. Hard links compare equal; distinct copies do not. Missing or inaccessible paths return an error.

fn setenv #

fn setenv(name string, value string, overwrite bool) int

setenv sets the value of an environment variable with name to value.

fn short_path #

fn short_path(path string) string

short_path is a Windows-only helper that returns the DOS 8.3 short path. On non-Windows platforms it simply returns the given path unchanged, so that callers guarded by $if windows { ... } type-check on other targets.

fn sigint_to_signal_name #

fn sigint_to_signal_name(si int) string

sigint_to_signal_name will translate si signal integer code to it's string code representation.

fn signal_ignore #

fn signal_ignore(args ...Signal)

signal_ignore to mask system signals, e.g.: signal_ignore(.pipe, .urg, ...).

fn signal_opt #

fn signal_opt(signum Signal, handler SignalHandler) !SignalHandler

signal will assign handler callback to be called when signum signal is received.

fn split_args #

fn split_args(input string) ![]string

split_args parses a directive or tool response into literal argv elements. Quotes and quoting backslash escapes group text; no shell expansion is performed.

fn split_path #

fn split_path(path string) (string, string, string)

split_path will split path into (dir,filename,ext). On Windows both / and \ separate path elements. On other systems \ does so only in a path that has no /. Examples:

dir,filename,ext := os.split_path('/usr/lib/test.so')
assert [dir,filename,ext] == ['/usr/lib','test','.so']

fn start_new_command #

@[deprecated: 'use os.start_new_command_args with an argument array to avoid shell injection']
fn start_new_command(cmd string) !Command

start_new_command will create a new os.Command, and start it right away. The command will represent a process running the passed shell command cmd, in a way that you can later call c.read_line() to intercept the new child process output line by line, streaming while the command is running. See also c.eof, c.read_line(), c.close() and c.exit_code .

fn start_new_command_args #

fn start_new_command_args(args []string) !CommandArgs

start_new_command_args starts a program with literal arguments and merged output. Use read_line(), eof, close(), and exit_code to stream its output. Standard input is empty; use Process for interactive input.

fn stat #

fn stat(path string) !Stat

stat returns a platform-agnostic Stat struct, containing metadata about the given file/folder path. It returns a POSIX error, if it can not do so.

Note: symlinks are followed, and the resulting Stat for their target will be returned. If this is not desired, call lstat/1 instead.

fn state_dir #

fn state_dir() string

state_dir returns a writable folder user-specific folder. It is suitable for storing state data, that should persist between (application) restarts, but that is not important or portable enough to the user that it should be stored in os.data_dir(). See: https://specifications.freedesktop.org/basedir-spec/latest/ . $XDG_STATE_HOME defines the base directory relative to which user-specific state files should be stored. If $XDG_STATE_HOME is either not set or empty, a default equal to $HOME/.local/state should be used. It may contain:* actions history (logs, history, recently used files, …)

  • current state of the application that can be reused on a restart (view, layout, open files, undo history, …)

Note: This function ensures that the returned directory exists and panics if directory creation fails.

fn stderr #

fn stderr() File

stderr returns an os.File for stderr.

fn stdin #

fn stdin() File

stdin returns an os.File for stdin.

fn stdio_capture #

fn stdio_capture() !IOCapture

or

    import os
    unbuffer_stdout()
    mut cap := os.stdio_capture()!
    println('hello println')
    eprintln('hello eprintln')
    eprintln('World eprintln')
    println('World println')
    sout, serr := cap.finish()
    assert sout == ['hello println\nWorld println\n']
    assert serr == ['hello eprintln\nWorld eprintln\n']

Example

   	import os
   	unbuffer_stdout()
   	mut cap := os.stdio_capture()!
   	println('hello println')
   	eprintln('hello eprintln')
   	cap.stop()
   	sout := cap.stdout.slurp()
   	serr := cap.stderr.slurp()
   	cap.close()
   	assert sout == ['hello println\n']
   	assert serr == ['hello eprintln\n']

fn stdout #

fn stdout() File

stdout returns an os.File for stdout.

fn system #

@[deprecated: 'use os.system_args with an argument array; command strings can allow shell injection']
fn system(cmd string) int

system works like exec, but only returns a return code.

fn system_args #

fn system_args(args []string) int

system_args runs a program with literal arguments and inherited standard streams. It waits for the program and returns its exit code without invoking a shell.

fn temp_dir #

fn temp_dir() string

temp_dir returns the path to a folder, that is suitable for storing temporary files.

fn to_slash #

fn to_slash(path string) string

to_slash returns the result of replacing each separator character in path with a slash (/).

fn truncate #

fn truncate(path string, len u64) !

truncate changes the size of the file located in path to len. Note that changing symbolic links on Windows only works as admin.

fn uname #

fn uname() Uname

uname returns information about the platform on which the program is running. For example: os.Uname{ sysname: 'Linux' nodename: 'nemesis' release: '5.15.0-57-generic' version: '#63~20.04.1-Ubuntu SMP Wed Nov 30 13:40:16 UTC 2022' machine: 'x86_64' } where the fields have the following meaning: sysname is the name of this implementation of the operating system nodename is the name of this node within an implementation-dependent communications network release is the current release level of this implementation version is the current version level of this release machine is the name of the hardware type, on which the system is running See also https://pubs.opengroup.org/onlinepubs/7908799/xsh/sysutsname.h.html

fn unsetenv #

fn unsetenv(name string) int

unsetenv clears an environment variable with name.

fn user_cache_dir #

fn user_cache_dir() !string

user_cache_dir returns the user cache directory: LOCALAPPDATA on Windows, or XDG_CACHE_HOME on POSIX. Empty values use AppData/Local or ~/.cache. A nonempty XDG_CACHE_HOME must be absolute.

fn user_config_dir #

fn user_config_dir() !string

user_config_dir returns the configuration directory: APPDATA on Windows, or XDG_CONFIG_HOME on POSIX. Empty values use AppData/Roaming or ~/.config. A nonempty XDG_CONFIG_HOME must be absolute.

fn user_home_dir #

fn user_home_dir() !string

user_home_dir returns the nonempty HOME directory on POSIX or USERPROFILE on Windows. Windows can also use HOMEDRIVE together with HOMEPATH. It returns an error when the platform's home variables are unavailable.

fn user_names #

fn user_names() ![]string

user_names returns an array containing the names of all users on the system.

fn user_os #

fn user_os() string

user_os returns the current user's operating system name.

fn utime #

fn utime(path string, actime i64, modtime i64) !

utime changes the access and modification times of the inode specified by path. It returns POSIX error message, if it can not do so.

fn vfopen #

fn vfopen(path string, mode string) !&C.FILE

vfopen returns an opened C file, given its path and open mode.

Note: os.vfopen is useful for compatibility with C libraries, that expect FILE *. If you write pure V code, os.create or os.open are more convenient.

fn vmodules_dir #

fn vmodules_dir() string

vmodules_dir returns the path to a folder, where v stores its global modules.

fn vmodules_paths #

fn vmodules_paths() []string

vmodules_paths returns a list of paths, where v looks up for modules. You can customize it through setting the environment variable VMODULES.

fn volume_name #

fn volume_name(path string) string

volume_name returns the Windows drive or UNC volume prefix of path, or an empty string on other platforms.

fn vtmp_dir #

fn vtmp_dir() string

vtmp_dir returns the path to a folder, that is writable to V programs, and specific to the OS user. It can be overridden by setting the env variable VTMP.

Note: This function ensures that the returned directory exists and panics if directory creation fails.

fn wait #

fn wait() int

wait blocks the calling process until one of its child processes exits or a signal is received. After child process terminates, parent continues its execution after wait system call instruction.

fn walk #

fn walk(path string, f fn (string))

walk traverses the given directory path. When a file is encountered, it will call the callback f with current file as argument. The entries of each directory are visited in the order of os.ls, which is not sorted and differs between platforms and filesystems. For a walk in lexical order, see: os.walk_dir

Note: walk can be called even for deeply nested folders, since it does not recurse, but processes them iteratively. For listing only one level deep, see: os.ls

fn walk_dir #

fn walk_dir(root string, cb WalkDirFn) !

walk_dir traverses the directory tree rooted at root and calls cb for every entry, directories included, in lexical order. It is the counterpart of Go's filepath.WalkDir.

Returning .skip_dir leaves the directory that was just reported unread, which is what makes pruning a large tree possible; on a non-directory it has no effect. Returning .stop ends the walk immediately, and walk_dir then returns no error. An entry that cannot be read, or a directory that cannot be listed, is reported through entry.err (see WalkDirFn) rather than aborting the walk, and walk_dir itself only fails when root is empty; a missing root is reported to the callback.

Symlinks are reported but never followed, and that includes a symlinked root; pass os.real_path(root) to walk the directory it points to.

Like walk, walk_dir iterates rather than recurses, so tree depth costs no stack.

Example

os.walk_dir('/srv/app', fn (path string, entry os.WalkDirEntry) os.WalkDirAction {
    if err := entry.err {
        eprintln('skipping ${path}: ${err}')
        return .proceed
    }
    if entry.is_dir && entry.name == '.git' {
        return .skip_dir
    }
    println(path)
    return .proceed
}) or { panic(err) }

fn walk_ext #

fn walk_ext(path string, ext string, opts WalkParams) []string

walk_ext returns a recursive list of all files in path ending with ext. The files of each directory come in the order of os.ls, which is not sorted and differs between platforms and filesystems. Call .sort() on the result when a stable order is needed. For listing only one level deep, see: os.ls

fn walk_with_context #

fn walk_with_context(path string, context voidptr, fcb FnWalkContextCB)

walk_with_context traverses the given directory path. For each encountered file and directory, it will call your fcb callback, passing it the arbitrary context in its first parameter, and the path to the file in its second parameter. The entries of each directory are visited in the order of os.ls, which is not sorted and differs between platforms and filesystems. For a walk in lexical order, see: os.walk_dir

Note: walk_with_context can be called even for deeply nested folders, since it does not recurse, but processes them iteratively. For listing only one level deep, see: os.ls

fn windows_volume #

Available on Windows only.

fn windows_volume(path string) string

windows_volume returns the volume name from the given path on a Windows system. An empty string is returned if no Windows volume is present. Examples (on a Windows system):

assert os.windows_volume(r'C:\path\to\file.v') == 'C:'
assert os.windows_volume('D:') == 'D:'
assert os.windows_volume(r'\\Host\share\files\file.v') == r'\\Host\share'

fn write_bytes #

@[manualfree]
fn write_bytes(path string, bytes []u8) !

write_bytes writes all the bytes to path.

fn write_file #

fn write_file(path string, text string) !

write_file writes text data to a file with the given path. If path already exists, it will be overwritten.

fn write_file_array #

fn write_file_array(path string, buffer array) !

write_file_array writes the data in buffer to a file in path. The file is closed on both success and write failure.

fn write_lines #

fn write_lines(path string, lines []string) !

write_lines writes the given array of lines to path. The lines are separated by \n .

fn AssetMode.from #

Available on Android only.

fn AssetMode.from[W](input W) !AssetMode

from returns the AssetMode value of an integer or of a field name, or an error if there is none.

fn ChildProcessPipeKind.from #

fn ChildProcessPipeKind.from[W](input W) !ChildProcessPipeKind

from returns the ChildProcessPipeKind value of an integer or of a field name, or an error if there is none.

fn FileBufferMode.from #

fn FileBufferMode.from[W](input W) !FileBufferMode

from returns the FileBufferMode value of an integer or of a field name, or an error if there is none.

fn FileType.from #

fn FileType.from[W](input W) !FileType

from returns the FileType value of an integer or of a field name, or an error if there is none.

fn MmapMode.from #

fn MmapMode.from[W](input W) !MmapMode

from returns the MmapMode value of an integer or of a field name, or an error if there is none.

fn ProcessState.from #

fn ProcessState.from[W](input W) !ProcessState

from returns the ProcessState value of an integer or of a field name, or an error if there is none.

fn SeekMode.from #

fn SeekMode.from[W](input W) !SeekMode

from returns the SeekMode value of an integer or of a field name, or an error if there is none.

fn Signal.from #

fn Signal.from[W](input W) !Signal

from returns the Signal value of an integer or of a field name, or an error if there is none.

fn WalkDirAction.from #

fn WalkDirAction.from[W](input W) !WalkDirAction

from returns the WalkDirAction value of an integer or of a field name, or an error if there is none.

type Asset #

Available on Android only.

type Asset = C.AAsset

fn (Asset) get_buffer #

Available on Android only.

fn (a &Asset) get_buffer() voidptr

get_buffer returns a pointer to a buffer holding the entire contents of the asset.

fn (Asset) get_length #

Available on Android only.

fn (a &Asset) get_length() int

get_length returns the total size of the asset data.

fn (Asset) get_length_64 #

Available on Android only.

fn (a &Asset) get_length_64() i64

get_length_64 returns the total size of the asset data using a 64-bit number instead of 32-bit as get_length.

fn (Asset) read #

Available on Android only.

fn (a &Asset) read(buffer voidptr, count usize) int

read attempts to read 'count' bytes of data from the current offset. read returns the number of bytes read, zero on EOF, or < 0 on error.

fn (Asset) close #

Available on Android only.

fn (a &Asset) close()

close closes the asset, freeing all associated resources.

type AssetManager #

Available on Android only.

type AssetManager = C.AAssetManager

AssetManager provides access to an application's raw assets by creating Asset objects.

fn (AssetManager) open #

Available on Android only.

fn (am &AssetManager) open(filename string, mode AssetMode) !&Asset

open opens an Android Asset.

type FN_SA_Handler #

type FN_SA_Handler = fn (sig int)

type FnWalkContextCB #

type FnWalkContextCB = fn (voidptr, string)

FnWalkContextCB is used to define the callback functions, passed to os.walk_context.

type HANDLE #

Available on Windows only.

type HANDLE = voidptr

Ref - https://docs.microsoft.com/en-us/windows/desktop/winprog/windows-data-types A handle to an object.

type HMODULE #

Available on Windows only.

type HMODULE = voidptr

type NativeActivity #

Available on Android only.

type NativeActivity = C.ANativeActivity

NativeActivity defines the native side of an android.app.NativeActivity.

type SignalHandler #

type SignalHandler = fn (Signal)

type VectoredExceptionHandler #

Available on Windows only.

type VectoredExceptionHandler = fn (&ExceptionPointers) u32

type WalkDirFn #

type WalkDirFn = fn (path string, entry WalkDirEntry) WalkDirAction

WalkDirFn is the callback type for walk_dir. entry.err is set in two cases, so a callback should look at it before relying on the other fields:- an entry that cannot be stat'ed is reported once, with is_dir and typ left at their zero values, so it is never descended into;- a directory that was reported normally but then cannot be listed is reported a second time, with err set and is_dir and typ still describing the directory. Returning .stop from that second report ends the walk; anything else carries on with the directory's next sibling.

enum AssetMode #

Available on Android only.

enum AssetMode {
	buffer    = C.AASSET_MODE_BUFFER // Caller plans to ask for a read-only buffer with all data.
	random    = C.AASSET_MODE_RANDOM // Read chunks, and seek forward and backward.
	streaming = C.AASSET_MODE_STREAMING // Read sequentially, with an occasional forward seek.
	unknown   = C.AASSET_MODE_UNKNOWN // No specific information about how data will be accessed.
}

enum ChildProcessPipeKind #

enum ChildProcessPipeKind {
	stdin
	stdout
	stderr
}

The kind of the pipe file descriptor, that is used for communicating with the child process

enum FileBufferMode #

enum FileBufferMode {
	fully_buffered = C._IOFBF // many characters are saved up and written as a block
	line_buffered  = C._IOLBF // characters are saved up until a newline is output or input is read from any stream attached to a terminal device (typically stdin)
	not_buffered   = C._IONBF // information appears on the destination file or terminal as soon as it is written
}

FileBufferMode describes the available buffering modes for an os.File: unbuffered, line buffered and block/fully buffered. Normally all files are block buffered. If a stream refers to a terminal (as stdout normally does), it is line buffered. The standard error stream stderr is always unbuffered by default.

enum FileType #

enum FileType {
	unknown
	regular
	directory
	character_device
	block_device
	fifo
	symbolic_link
	socket
}

enum MmapMode #

enum MmapMode {
	read_only
	read_write
}

MmapMode selects the protection of a memory mapping.

enum ProcessState #

enum ProcessState {
	not_started
	running
	stopped
	exited
	aborted
	closed
}
  • ProcessState.not_started - the process has not yet started
  • ProcessState.running - the process is currently running
  • ProcessState.stopped - the process was running, but was stopped temporarily
  • ProcessState.exited - the process has finished/exited
  • ProcessState.aborted - the process was terminated by a signal
  • ProcessState.closed - the process resources like opened file descriptors were freed/discarded, final state.

enum SeekMode #

enum SeekMode {
	start
	current
	end
}

enum Signal #

enum Signal {
	hup    = 1 // hangup
	int    = 2 // interrupt from keyboard
	quit   = 3 // quit from keyboard
	ill    = 4 // illegal instruction
	trap   = 5 // trace trap
	abrt   = 6 // abort
	bus    = 7 // bus error
	fpe    = 8 // floating point exception
	kill   = 9 // kill signal
	usr1   = 10 // user-defined signal 1
	segv   = 11 // segmentation violation
	usr2   = 12 // user-defined signal 2
	pipe   = 13 // write on a pipe with no one to read it
	alrm   = 14 // alarm clock
	term   = 15 // software termination signal
	stkflt = 16 // stack fault
	chld   = 17 // child process has stopped or exited
	cont   = 18 // continue executing, if stopped
	stop   = 19 // stop executing (cannot be caught or ignored)
	tstp   = 20 // stop executing, can be caught and ignored
	ttin   = 21 // terminal input for background process
	ttou   = 22 // terminal output for background process
	urg    = 23 // urgent condition on socket
	xcpu   = 24 // CPU time limit exceeded
	xfsz   = 25 // file size limit exceeded
	vtalrm = 26 // virtual time alarm
	prof   = 27 // profiling timer alarm
	winch  = 28 // window size change
	poll   = 29 // pollable event occurred
	pwr    = 30 // power failure
	sys    = 31 // bad system call
}

enum WalkDirAction #

enum WalkDirAction {
	proceed  // carry on with the next entry
	skip_dir // do not descend into the directory that was just reported
	stop     // end the walk
}

WalkDirAction tells walk_dir what to do after its callback returns.

struct C.AAsset #

Available on Android only.

struct C.AAsset {
}

struct C.AAssetManager #

Available on Android only.

struct C.AAssetManager {
}

struct C.ANativeActivity #

Available on Android only.

struct C.ANativeActivity {
pub:
	assetManager     &AssetManager = unsafe { nil } // Pointer to the Asset Manager instance for the application.
	clazz            voidptr // (jobject) The NativeActivity object handle.
	env              voidptr // (JNIEnv *) JNI context for the main thread of the app.
	externalDataPath &char   // Path to this application's external (removable/mountable) data directory.
	instance         voidptr // This is the native instance of the application.
	internalDataPath &char   // Path to this application's internal data directory.
	obbPath          &char   // Available starting with Honeycomb: path to the directory containing the application's OBB files (if any).
	sdkVersion       int     // The platform's SDK version code.
	vm               voidptr // (JavaVM *) The global handle on the process's Java VM.
}

See https://developer.android.com/ndk/reference/struct/a-native-activity for more info.

struct C.__stat64 #

Available on all platforms except Linux and Windows.

struct C.__stat64 {
	st_size  u64
	st_mode  u32
	st_mtime i64
}

Available on Linux only.

struct C.__stat64 {
	st_mode  u32
	st_size  u64
	st_mtime u64
}

Available on Windows only.

struct C.__stat64 {
	st_dev   u32 // 4
	st_ino   u16 // 2
	st_mode  u16 // 2
	st_nlink u16 // 2
	st_uid   u16 // 2
	st_gid   u16 // 2
	st_rdev  u32 // 4
	st_size  u64 // 8
	st_atime i64 // 8
	st_mtime i64 // 8
	st_ctime i64 // 8
}

struct C.dirent #

struct C.dirent {
	d_ino     u64
	d_seekoff u64
	d_reclen  u16
	d_namlen  u16
	d_type    u8
	d_name    [256]char
}

struct C.fd_set #

@[typedef]
struct C.fd_set {}

struct C.sigaction #

struct C.sigaction {
mut:
	sa_mask      int
	sa_sigaction int
	sa_flags     int
	sa_handler   FN_SA_Handler
}

struct C.sigset_t #

@[typedef]

Available on Linux only.

struct C.sigset_t {}

struct C.stat #

Available on macOS only.

struct C.stat {
	st_dev           i32
	st_mode          u16
	st_nlink         u16
	st_ino           u64
	st_uid           u32
	st_gid           u32
	st_rdev          i32
	st_atime         i64
	st_atimensec     i64
	st_mtime         i64
	st_mtimensec     i64
	st_ctime         i64
	st_ctimensec     i64
	st_birthtime     i64
	st_birthtimensec i64
	st_size          i64
	st_blocks        i64
	st_blksize       i32
	st_flags         u32
	st_gen           u32
	st_lspare        i32
	st_qspare        [2]i64
}

Available on all platforms except Linux, macOS and Windows.

struct C.stat {
	st_dev   u64
	st_ino   u64
	st_mode  u32
	st_nlink u64
	st_uid   u32
	st_gid   u32
	st_rdev  u64
	st_size  u64
	st_atime i64
	st_mtime i64
	st_ctime i64
}

Minimal stat struct as specified in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html

Available on Linux only.

struct C.stat {
	st_dev     u64 // 8
	st_ino     u64 // 8
	st_nlink   u64 // 8
	st_mode    u32 // 4
	st_uid     u32 // 4
	st_gid     u32 // 4
	st_rdev    u64 // 8
	st_size    u64 // 8
	st_blksize u64 // 8
	st_blocks  u64 // 8
	st_atime   i64 // 8
	st_mtime   i64 // 8
	st_ctime   i64 // 8
}

Available on Windows only.

struct C.stat {
	st_dev   u64
	st_ino   u64
	st_mode  u32
	st_nlink u64
	st_uid   u32
	st_gid   u32
	st_rdev  u64
	st_size  u64
	st_atime int
	st_mtime int
	st_ctime int
}

Minimal stat struct as specified in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html

struct C.timespec #

struct C.timespec {
pub mut:
	tv_sec  i64
	tv_nsec i64
}

struct C.timeval #

struct C.timeval {
pub:
	tv_sec  u64
	tv_usec u64
}

struct C.utimbuf #

struct C.utimbuf {
	actime  i64
	modtime i64
}

struct C.utsname #

struct C.utsname {
mut:
	sysname  &char
	nodename &char
	release  &char
	version  &char
	machine  &char
}

struct Command #

struct Command {
mut:
	f voidptr
pub mut:
	eof       bool
	exit_code int
pub:
	path            string
	redirect_stdout bool
}

Command represents a running shell command, that the parent process wishes to monitor for output on its stdout pipe.

fn (Command) start #

@[deprecated: 'use os.start_new_command_args with an argument array to avoid shell injection']
@[manualfree]
fn (mut c Command) start() !

start will start the command. Use start_new_command/1 instead.

fn (Command) read_line #

@[manualfree]
fn (mut c Command) read_line() string

read_line returns a single line from the stdout of the running command.

Note: c.eof will be set to true, if the command ended while a line was read. The returned line will contain all of the accumulated output before the process ended. In practice, that often means, you will get a single '' and c.eof == true at the end.

fn (Command) close #

fn (mut c Command) close() !

close will close the pipe to the command, and wait for the command to finish, then set .exit_code according to how its final process status.

struct CommandArgs #

struct CommandArgs {
mut:
	process &Process = unsafe { nil }
	pending string
pub mut:
	eof       bool
	exit_code int
pub:
	path string
}

CommandArgs streams merged output from a program started with literal arguments.

fn (CommandArgs) read_line #

@[manualfree]
fn (mut c CommandArgs) read_line() string

read_line waits for the next output line without its newline, setting eof when the pipe closes.

fn (CommandArgs) close #

fn (mut c CommandArgs) close() !

close closes the output pipe, waits for the program, and records its exit code.

struct ContextRecord #

Available on Windows only.

struct ContextRecord {
	// TODO
}

struct CopyParams #

@[params]
struct CopyParams {
pub:
	fail_if_exists bool
}

struct DiskUsage #

struct DiskUsage {
pub:
	total     u64
	available u64
	used      u64
}

struct Eof #

struct Eof {
	Error
}

Eof error means that we reach the end of the file.

struct ExceptionPointers #

Available on Windows only.

struct ExceptionPointers {
pub:
	exception_record &ExceptionRecord = unsafe { nil }
	context_record   &ContextRecord   = unsafe { nil }
}

struct ExceptionRecord #

Available on Windows only.

struct ExceptionRecord {
pub:
	// status_ constants
	code        u32
	flags       u32
	record      &ExceptionRecord = unsafe { nil }
	address     voidptr
	param_count u32
	// params []voidptr
}

struct ExecutableNotFoundError #

struct ExecutableNotFoundError {
	Error
}

fn (ExecutableNotFoundError) msg #

fn (err ExecutableNotFoundError) msg() string

struct Fifo #

@[heap]
struct Fifo {
mut:
	file      File
	handle    voidptr
	is_server bool
}

Fifo is a named-pipe endpoint for IPC between related or unrelated processes. The server creates the endpoint and blocks waiting for a client; the client connects to it. Afterwards bytes flow in one direction: client writes, server reads (open a second pair for duplex). It is the cross-platform form of POSIX fifos and Windows named pipes.

fn (Fifo) read #

fn (f &Fifo) read(mut buf []u8) !int

read reads up to buf.len bytes. It mirrors File.read.

fn (Fifo) write #

fn (mut f Fifo) write(buf []u8) !int

write writes buf. It mirrors File.write.

fn (Fifo) close #

fn (mut f Fifo) close()

close releases the endpoint.

struct File #

struct File {
mut:
	cfile voidptr // Using void* instead of FILE*
pub:
	fd int
pub mut:
	is_opened bool
}

fn (File) eof #

fn (f &File) eof() bool

eof returns true, when the end of file has been reached.

fn (File) reopen #

fn (mut f File) reopen(path string, mode string) !

reopen allows a File to be reused. It is mostly useful for reopening standard input and output.

fn (File) read #

fn (f &File) read(mut buf []u8) !int

read implements the Reader interface.

fn (File) write #

fn (mut f File) write(buf []u8) !int

write implements the Writer interface. It returns how many bytes were actually written.

fn (File) writeln #

fn (mut f File) writeln(s string) !int

writeln writes the string s into the file, and appends a \n character. It returns how many bytes were written, including the \n character.

fn (File) write_string #

fn (mut f File) write_string(s string) !int

write_string writes the string s into the file. It returns how many bytes were actually written.

fn (File) write_to #

fn (mut f File) write_to(pos u64, buf []u8) !int

write_to implements the RandomWriter interface. It returns how many bytes were actually written. It resets the seek position to the end of the file.

fn (File) write_ptr #

@[unsafe]
fn (mut f File) write_ptr(data voidptr, size int) int

write_ptr writes size bytes to the file, starting from the address in data.

Note: write_ptr is unsafe and should be used carefully, since if you pass invalid pointers to it, it will cause your programs to segfault.

fn (File) write_full_buffer #

@[unsafe]
fn (mut f File) write_full_buffer(buffer voidptr, buffer_len usize) !

write_full_buffer writes a whole buffer of data to the file, starting from the address in buffer, no matter how many tries/partial writes it would take. The size in bytes, of the buffer, should be passed in buffer_len.

fn (File) write_ptr_at #

@[unsafe]
fn (mut f File) write_ptr_at(data voidptr, size int, pos u64) int

write_ptr_at writes size bytes to the file, starting from the address in data, at byte offset pos, counting from the start of the file (pos 0).

Note: write_ptr_at is unsafe and should be used carefully, since if you pass invalid pointers to it, it will cause your programs to segfault.

fn (File) read_bytes #

fn (f &File) read_bytes(size int) []u8

read_bytes reads size bytes from the beginning of the file. Utility method, same as .read_bytes_at(size, 0).

fn (File) read_bytes_at #

fn (f &File) read_bytes_at(size int, pos u64) []u8

read_bytes_at reads size bytes at the given position in the file.

fn (File) read_bytes_with_newline #

fn (f &File) read_bytes_with_newline(mut buf []u8) !int

read_bytes_with_newline reads from the current position of the file into the provided buffer. Each consecutive call on the same file, continues reading, from where it previously ended. A read call is either stopped, if the buffer is full, a newline was read or EOF. On EOF, the method returns 0. The methods will also return any IO error encountered.

fn (File) read_bytes_into #

fn (f &File) read_bytes_into(pos u64, mut buf []u8) !int

read_bytes_into fills buf with bytes at the given position in the file. buf must have length greater than zero. Returns the number of read bytes, or an error.

fn (File) read_from #

fn (f &File) read_from(pos u64, mut buf []u8) !int

read_from implements the RandomReader interface.

fn (File) read_into_ptr #

fn (f &File) read_into_ptr(ptr &u8, max_size int) !int

read_into_ptr reads at most max_size bytes from the file and writes it into ptr. Returns the amount of bytes read or an error.

fn (File) flush #

fn (mut f File) flush()

flush writes any buffered unwritten data left in the file stream.

fn (File) read_struct #

fn (mut f File) read_struct[T](mut t T) !

read_struct reads a single plain-data struct of type T. T must not contain strings, dynamic arrays, maps, pointers, interfaces, or function values.

fn (File) read_struct_at #

fn (mut f File) read_struct_at[T](mut t T, pos u64) !

read_struct_at reads a single plain-data struct of type T at position specified in file. T must not contain strings, dynamic arrays, maps, pointers, interfaces, or function values.

fn (File) read_raw #

fn (mut f File) read_raw[T]() !T

read_raw reads and returns a single plain-data instance of type T. T must not contain strings, dynamic arrays, maps, pointers, interfaces, or function values.

fn (File) read_raw_at #

fn (mut f File) read_raw_at[T](pos u64) !T

read_raw_at reads and returns a single plain-data instance of type T starting at file byte offset pos. T must not contain strings, dynamic arrays, maps, pointers, interfaces, or function values.

fn (File) write_struct #

fn (mut f File) write_struct[T](t &T) !

write_struct writes a single plain-data struct of type T. T must not contain strings, dynamic arrays, maps, pointers, interfaces, or function values.

fn (File) write_struct_at #

fn (mut f File) write_struct_at[T](t &T, pos u64) !

write_struct_at writes a single plain-data struct of type T at file byte offset pos. T must not contain strings, dynamic arrays, maps, pointers, interfaces, or function values.

fn (File) write_raw #

fn (mut f File) write_raw[T](t &T) !

write_raw writes a single plain-data instance of type T. T must not contain strings, dynamic arrays, maps, pointers, interfaces, or function values.

fn (File) write_raw_at #

fn (mut f File) write_raw_at[T](t &T, pos u64) !

write_raw_at writes a single plain-data instance of type T starting at file byte offset pos. T must not contain strings, dynamic arrays, maps, pointers, interfaces, or function values.

fn (File) seek #

fn (mut f File) seek(pos i64, mode SeekMode) !

seek moves the file cursor (if any) associated with a file to a new location, offset pos bytes from the origin. The origin is dependent on the mode and can be: .start -> the origin is the start of the file .current -> the current position/cursor in the file .end -> the end of the file If the file is not seek-able, or an error occurs, the error will be returned to the caller. A successful call to the fseek() function clears the end-of-file indicator for the file.

fn (File) tell #

fn (f &File) tell() !i64

tell will return the current offset of the file cursor measured from the start of the file, in bytes. It is complementary to seek, i.e. you can use the return value as the pos parameter to .seek( pos, .start ), so that your next read will happen from the same place.

fn (File) setvbuf #

@[unsafe]
fn (mut f File) setvbuf(buffer &char, mode FileBufferMode, size usize) int

setvbuf sets the buffer and buffering mode for the given file f. See also os.FileBufferMode. It returns 0 on success. It returns nonzero on failure (the mode is invalid, or the request cannot be honored). Except for unbuffered files, the buffer argument should point to a buffer at least size bytes long; this buffer will be used instead of the current buffer. If the argument buffer is nil, only the mode is affected; a new buffer will be allocated on the next read or write operation.

Note: make sure, that the space, that buffer points to (when != 0), still exists by the time the file stream is closed, which also happens at program termination.

Note: f.setvbuf() may be used only after opening a file stream, and before any other operations have been performed on it.

fn (File) set_buffer #

fn (mut f File) set_buffer(mut buffer []u8, mode FileBufferMode) int

set_buffer sets the buffer for the file, and the file buffering mode (see also os.FileBufferMode). Unlike File.setvbuf, it allows you to pass an existing V []u8 array directly.

Note: f.set_buffer() may be used only after opening a file stream, and before any other operations have been performed on it.

fn (File) set_line_buffered #

fn (mut f File) set_line_buffered()

set_line_buffered sets the file buffering mode to FileBufferMode.line_buffered.

Note: f.set_line_buffered() may be used only after opening a file stream, and before any other operations have been performed on it.

fn (File) set_unbuffered #

fn (mut f File) set_unbuffered()

set_unbuffered sets the file buffering mode to FileBufferMode.not_buffered.

Note: f.set_unbuffered() may be used only after opening a file stream, and before any other operations have been performed on it.

fn (File) write_le #

fn (mut f File) write_le[T](data T) !

write_le writes an unsigned number value to the file. It assumes that the value should be stored in a little endian order. If the machine is a big endian one, it will first convert the big endian value to a little endian one. It is safe to use as a cross platform way to write data, for which you have to use a predefined order (defined in a file format spec).

fn (File) write_be #

fn (mut f File) write_be[T](data T) !

write_be writes an unsigned number value to the file. It assumes that the value should be stored in a big endian order. If the machine is a little endian one, it will first convert the little endian value to a big endian one. It is safe to use as a cross platform way to write data, for which you have to use a predefined order (defined in a file format spec).

fn (File) read_le #

fn (mut f File) read_le[T]() !T

read_le reads an unsigned number value from the file. It assumes that the value was stored in a little endian order. If the machine is a big endian one, it will convert the value to a big endian one. It is intended to use as a cross platform way to read data, for which the order is known (from the file format spec).

fn (File) read_be #

fn (mut f File) read_be[T]() !T

read_be reads an unsigned number value from the file. It assumes that the value was stored in a big endian order. If the machine is a little endian one, it will convert the value to a little endian one. It is intended to use as a cross platform way to read data, for which the order is known (from the file format spec).

fn (File) write_u8 #

fn (mut f File) write_u8(b u8) !

write_u8 writes a single byte value to the file f.

Note: if possible, use some of the other APIs, that write larger chunks of data, before using write_u8/1.

fn (File) read_u8 #

fn (mut f File) read_u8() !u8

read_u8 reads a single byte value from the file f.

Note: if possible, use some of the other APIs, that read larger chunks of data, before using read_u8/1.

fn (File) close #

fn (mut f File) close()

struct FileInfo #

struct FileInfo {
	FileMode
pub:
	size  u64 // size of the file in bytes
	mtime i64 // last modification time in seconds after the Unix epoch
}

struct FileMode #

struct FileMode {
pub:
	typ    FileType
	owner  FilePermission
	group  FilePermission
	others FilePermission
}

fn (FileMode) bitmask #

fn (m FileMode) bitmask() u32

bitmask returns a 9 bit sequence in the order owner + group + others. This is a valid bitmask to use with os.chmod.

struct FileNotOpenedError #

struct FileNotOpenedError {
	Error
}

fn (FileNotOpenedError) msg #

fn (err FileNotOpenedError) msg() string

struct FilePermission #

struct FilePermission {
pub:
	read    bool
	write   bool
	execute bool
}

fn (FilePermission) bitmask #

fn (p FilePermission) bitmask() u32

bitmask returns a 3 bit sequence in the order RWE, where the bit is set to 1 if the value is true or 0 otherwise.

struct IOCapture #

@[noinit]
struct IOCapture {
pub mut:
	stdout Pipe
	stderr Pipe
mut:
	original_stdout_fd int = -1
	original_stderr_fd int = -1
}

IOCapture manages redirection of standard output and error streams

fn (IOCapture) stop #

fn (mut c IOCapture) stop()

stop restores the original stdout and stderr streams. This should be called to resume normal console output

fn (IOCapture) close #

fn (mut c IOCapture) close()

close releases all resources associated with the capture.

fn (IOCapture) finish #

fn (mut c IOCapture) finish() ([]string, []string)

finish stops capturing, reads all captured data, and releases resources.

struct MkdirParams #

@[params]
struct MkdirParams {
pub:
	mode u32 = 0o777 // note that the actual mode is affected by the process's umask
}

struct Mmap #

@[heap]
struct Mmap {
mut:
	data        []u8
	mode        MmapMode
	mapping     voidptr // Windows file-mapping handle; nil elsewhere
	file_handle voidptr // Windows file handle retained for durable sync
}

Mmap is a memory-mapped file region: the file (or its prefix) is visible as bytes, backed by the OS page cache. Writes through a read_write mapping reach the file after sync (or OS page-out). The bytes() view must not be used after close.

fn (Mmap) bytes #

@[unsafe]
fn (m &Mmap) bytes() []u8

bytes returns the mapped region as a zero-copy byte view. The caller must keep the mapping open while using the view, must not resize or free the view, and must not mutate a read_only view. The file must not be truncated while the mapping is in use.

fn (Mmap) len #

fn (m &Mmap) len() u64

len returns the mapped length in bytes.

fn (Mmap) sync #

fn (mut m Mmap) sync() !

sync flushes writes through a read_write mapping to the file. It returns an error for read-only or closed mappings.

fn (Mmap) close #

fn (mut m Mmap) close()

close unmaps the region and releases all handles. The bytes() view must not be used afterwards. Closing twice is a no-op.

struct MvParams #

@[params]
struct MvParams {
pub:
	overwrite bool = true
}

struct NotExpected #

struct NotExpected {
	cause string
	code  int
}

NotExpected is a generic error that means that we receave a not expected error.

struct Pipe #

@[noinit]
struct Pipe {
pub mut:
	read_fd  int = -1
	write_fd int = -1
}

Pipe represents a bidirectional communication channel

fn (Pipe) close #

fn (mut p Pipe) close()

close closes the pipe and releases associated resources.

fn (Pipe) read #

fn (p &Pipe) read(mut buffer []u8) !int

read reads data from the pipe into the provided buffer.

fn (Pipe) write #

fn (p &Pipe) write(buffer []u8) !int

write writes data from the buffer to the pipe.

fn (Pipe) write_string #

fn (p &Pipe) write_string(s string) !int

write_string writes data from the string to the pipe.

fn (Pipe) slurp #

fn (mut p Pipe) slurp() []string

slurp reads all data from the pipe until EOF.

struct Process #

@[heap]
struct Process {
pub mut:
	filename         string // the process's command file path
	pid              int    // the PID of the process
	code             int          = -1           // the exit code; on Windows this is a signed 32-bit value, so an exited child can also return -1
	status           ProcessState = .not_started // the current status of the process
	err              string   // if the process fails, contains the reason why
	args             []string // the arguments that the command takes
	work_folder      string   // the initial working folder of the process. When '', reuse the same folder as the parent process.
	env_is_custom    bool     // true, when the environment was customized with .set_environment
	env              []string // the environment with which the process was started  (list of 'var=val')
	use_stdio_ctl    bool     // when true, then you can use p.stdin_write(), p.stdout_slurp() and p.stderr_slurp()
	stdin_path       string   // when non-empty, use this file as the child process's standard input
	has_stdin_path   bool     // true after set_stdin_path is called
	use_pgroup       bool     // when true, the process will create a new process group, enabling .signal_pgkill()
	stdio_fd         [3]int   // the stdio file descriptors for the child process, used only by the nix implementation
	wdata            voidptr  // the WProcess; used only by the windows implementation
	create_no_window bool     // sets a value indicating whether to start the process in a new window, The default is false; used only by the windows implementation
mut:
	expand_environment bool // Process arguments are literal, including environment references on Windows
	merge_stdio        bool // when true, redirect the child's stderr to its stdout pipe
	reaped             bool // the child's exit status has already been collected
}

fn (Process) signal_kill #

fn (mut p Process) signal_kill()

signal_kill kills the process, after that it is no longer running. Call wait afterward to collect its exit status and release its resources.

fn (Process) signal_term #

fn (mut p Process) signal_term()

signal_term terminates the process.

fn (Process) signal_pgkill #

fn (mut p Process) signal_pgkill()

signal_pgkill kills the whole process group.

fn (Process) signal_stop #

fn (mut p Process) signal_stop()

signal_stop stops the process, you can resume it with p.signal_continue().

fn (Process) signal_continue #

fn (mut p Process) signal_continue()

signal_continue tell a stopped process to continue/resume its work.

fn (Process) wait #

fn (mut p Process) wait()

wait waits for a process to finish, including one killed with signal_kill.

Note: You have to call p.wait(), otherwise a finished process would get to a zombie state, and its resources will not get released fully, until its parent process exits.

Note: This call will block the calling process until the child process is finished.

fn (Process) close #

fn (mut p Process) close()

close frees the OS resources associated with the process. It can be called multiple times, but will free the resources just once. If the process has already finished, this sets the process state to .closed, which is final.

fn (Process) free #

@[unsafe]
fn (mut p Process) free()

fn (Process) is_alive #

fn (mut p Process) is_alive() bool

is_alive query whether the process is still alive.

fn (Process) set_redirect_stdio #

fn (mut p Process) set_redirect_stdio()

fn (Process) set_redirect_stdio_merged #

fn (mut p Process) set_redirect_stdio_merged()

set_redirect_stdio_merged redirects both stdout and stderr to the stdout pipe.

fn (Process) stdin_write #

fn (mut p Process) stdin_write(s string)

stdin_write will write the string s, to the stdin pipe of the child process.

fn (Process) stdout_slurp #

fn (mut p Process) stdout_slurp() string

stdout_slurp will read from the stdout pipe. It will block until it either reads all the data, or until the pipe is closed (end of file).

fn (Process) stderr_slurp #

fn (mut p Process) stderr_slurp() string

stderr_slurp will read from the stderr pipe. It will block until it either reads all the data, or until the pipe is closed (end of file).

fn (Process) stdout_read #

fn (mut p Process) stdout_read() string

stdout_read reads a block of data from the child process stdout pipe. It returns '' immediately when there is currently no data to be read.

fn (Process) stderr_read #

fn (mut p Process) stderr_read() string

stderr_read reads a block of data from the child process stderr pipe. It returns '' immediately when there is currently no data to be read.

fn (Process) pipe_read #

fn (mut p Process) pipe_read(pkind ChildProcessPipeKind) ?string

pipe_read reads a block of data, from the given pipe of the child process. It will return none, if there is no data to be read, without blocking.

fn (Process) is_pending #

fn (mut p Process) is_pending(pkind ChildProcessPipeKind) bool

is_pending returns whether there is data to be read from child process's pipe corresponding to pkind. For example if p.is_pending(.stdout) { dump( p.stdout_read() ) } will not block indefinitely.

fn (Process) run #

fn (mut p Process) run()

run starts the new process.

fn (Process) set_args #

fn (mut p Process) set_args(pargs []string)

set_args - set the arguments for the new process. Pass literal arguments without shell quoting or escaping.

fn (Process) set_work_folder #

fn (mut p Process) set_work_folder(path string)

set_work_folder - set the initial working folder for the new process. If you do not set it, it will reuse the current working folder of the parent process.

fn (Process) set_environment #

fn (mut p Process) set_environment(envs map[string]string)

set_environment - set a custom environment variable mapping for the new process.

fn (Process) set_stdin_path #

fn (mut p Process) set_stdin_path(path string)

set_stdin_path configures the new process to inherit an open file as its standard input instead of creating a writable parent-side stdin pipe.

struct Result #

struct Result {
pub:
	exit_code int
	output    string
	// stderr string // TODO
}

fn (Result) free #

@[unsafe]
fn (mut result Result) free()

struct SizeOfTypeIs0Error #

struct SizeOfTypeIs0Error {
	Error
}

fn (SizeOfTypeIs0Error) msg #

fn (err SizeOfTypeIs0Error) msg() string

struct Stat #

struct Stat {
pub:
	dev   u64 // ID of device containing file
	inode u64 // Inode number
	mode  u32 // File type and user/group/world permission bits
	nlink u64 // Number of hard links to file
	uid   u32 // Owner user ID
	gid   u32 // Owner group ID
	rdev  u64 // Device ID (if special file)
	size  u64 // Total size in bytes
	atime i64 // Last access (seconds since UNIX epoch)
	mtime i64 // Last modified (seconds since UNIX epoch)
	ctime i64 // Last status change (seconds since UNIX epoch)
}

Stat struct modeled on POSIX.

fn (Stat) get_filetype #

fn (st Stat) get_filetype() FileType

get_filetype returns the FileType from the Stat struct.

fn (Stat) get_mode #

fn (st Stat) get_mode() FileMode

get_mode returns the file type and permissions (readable, writable, executable) in owner/group/others format.

struct SystemError #

@[params]
struct SystemError {
pub:
	msg  string
	code int = error_code_not_set
}

struct Uname #

struct Uname {
pub mut:
	sysname  string
	nodename string
	release  string
	version  string
	machine  string
}

struct WProcess #

Available on Windows only.

struct WProcess {
pub mut:
	proc_info         ProcessInformation
	command_line      [65536]u8
	child_stdin_read  &u32 = unsafe { nil }
	child_stdin_write &u32 = unsafe { nil }

	child_stdout_read  &u32 = unsafe { nil }
	child_stdout_write &u32 = unsafe { nil }

	child_stderr_read  &u32 = unsafe { nil }
	child_stderr_write &u32 = unsafe { nil }
}

struct WalkDirEntry #

struct WalkDirEntry {
pub:
	name   string // the entry's base name, without any directory part
	is_dir bool   // true for a directory; symlinks are reported, never followed
	typ    FileType
	err    ?IError // why the entry could not be read or listed; none when it could
}

WalkDirEntry describes one entry visited by walk_dir.

struct WalkParams #

@[params]
struct WalkParams {
pub:
	hidden bool
}