file
import std::fs::file; · source
Types
File
type struct File {
fd: i32;
static open(p: Path) -> Result<File, IoError>;
static create(p: Path) -> Result<File, IoError>;
static open_with(p: Path, options: &OpenOptions) -> Result<File, IoError>;
seek_set(mut &this, offset: i64) -> Result<u64, IoError>;
seek_cur(mut &this, offset: i64) -> Result<u64, IoError>;
seek_end(mut &this, offset: i64) -> Result<u64, IoError>;
}
import std::fs::file;
import std::fs::path;
match (File::open(Path::from(Str::new("config.json")))) {
Result::Ok(f) => { /* f is Read + Write + Seek */ }
Result::Err(e) => { /* NotFound, PermissionDenied, ... */ }
}
open is read-only, create creates or truncates for writing with mode 0644, and open_with takes an OpenOptions for full control. File implements Read, Write, and Seek, plus the inherent seek_set, seek_cur, and seek_end helpers for direct use; stream_position comes with Seek.
A
Filewraps a raw fd, and the obligations are the POSIX ones: every open pairs with exactly one drop, which closes it. Callingdroptwice is a bug the kernel may not catch — the secondclosecould race an unrelatedopenthat reused the descriptor.
Properties
| Property | Type |
|---|---|
fd | i32 |
Constructors
static open(p: Path) -> Result<File, IoError>;
static open(p: Path) -> Result<File, IoError>;Open p for reading. Fails with NotFound, PermissionDenied, or a mapped errno-derived kind on failure.
static create(p: Path) -> Result<File, IoError>;
static create(p: Path) -> Result<File, IoError>;Create (or truncate) p for writing.
static open_with(p: Path, options: &OpenOptions) -> Result<File, IoError>;
Methods
seek_set(mut &this, offset: i64) -> Result<u64, IoError>;
seek_set(mut &this, offset: i64) -> Result<u64, IoError>;Seek to offset bytes from the start. Returns the new absolute position.
seek_cur(mut &this, offset: i64) -> Result<u64, IoError>;
seek_cur(mut &this, offset: i64) -> Result<u64, IoError>;Seek by offset bytes relative to the current position (offset may be negative). Returns the new absolute position.
seek_end(mut &this, offset: i64) -> Result<u64, IoError>;
seek_end(mut &this, offset: i64) -> Result<u64, IoError>;Seek to offset bytes relative to the end of the file (offset is usually <= 0). Returns the new absolute position.
OpenOptions
type struct OpenOptions {
read: boolean;
write: boolean;
append: boolean;
truncate: boolean;
create: boolean;
create_new: boolean;
static new() -> OpenOptions;
read(mut &this, value: boolean) -> OpenOptions;
write(mut &this, value: boolean) -> OpenOptions;
append(mut &this, value: boolean) -> OpenOptions;
truncate(mut &this, value: boolean) -> OpenOptions;
create(mut &this, value: boolean) -> OpenOptions;
create_new(mut &this, value: boolean) -> OpenOptions;
open(&this, p: Path) -> Result<File, IoError>;
to_flags(&this) -> i32;
}
A builder. Each setter takes a boolean and returns the options, so they chain; open(p) finishes. to_flags is the O_* bitmask the options translate to, for handing to libc::open directly.
mut opts: OpenOptions = OpenOptions::new();
mut log: File = opts.write(true).create(true).append(true).open(p)?;
Properties
| Property | Type |
|---|---|
read | boolean |
write | boolean |
append | boolean |
truncate | boolean |
create | boolean |
create_new | boolean |
Constructors
static new() -> OpenOptions;
Methods
read(mut &this, value: boolean) -> OpenOptions;
write(mut &this, value: boolean) -> OpenOptions;
append(mut &this, value: boolean) -> OpenOptions;
truncate(mut &this, value: boolean) -> OpenOptions;
create(mut &this, value: boolean) -> OpenOptions;
create_new(mut &this, value: boolean) -> OpenOptions;
open(&this, p: Path) -> Result<File, IoError>;
to_flags(&this) -> i32;
to_flags(&this) -> i32;Flatten the options into the platform open/_open flags bitmask. The actual flag values are OS-specific (glibc and MSVCRT disagree on O_CREAT/O_TRUNC/O_APPEND/O_EXCL), so the bit assembly lives in the per-OS open_flags_for helpers below; a method body can't be ![target(...)]-gated, but a free function can.
Trait implementations
implement trait Seek for struct File
implement trait Drop for struct File
implement trait Read for struct File
implement trait Write for struct File
flush is a no-op: the file is unbuffered at this layer, and write_some goes straight to write(2).
Free Functions
Whole-file helpers
| Function | Notes |
|---|---|
read(p) | The whole file as bytes. |
read_to_string(p) | Bytes taken verbatim, no UTF-8 validation. |
write(p, bytes) | Creates or truncates. |
copy(from, to) | Bytes copied. |
copy creates to if missing, truncates it if present, then applies the source's Unix permission bits, mirroring cp. The source must be a regular file — copying a directory fails with InvalidInput. On a mid-copy failure the partially written destination is left in place and the error is returned as-is.
function read(p: Path) -> Result<Array<u8>, IoError>;
function read(p: Path) -> Result<Array<u8>, IoError>;Read the entire contents of p into a fresh Array<u8>. Panics on allocation failure; caller handles I/O failure via the Result.
function read_to_string(p: Path) -> Result<String, IoError>;
function read_to_string(p: Path) -> Result<String, IoError>;Read the entire contents of p into a fresh String. The bytes are taken verbatim; no UTF-8 validation is performed (the caller is responsible for that if it matters). Panics on allocation failure; I/O failure surfaces through the Result.
function write(p: Path, bytes: Slice<u8>) -> Result<(), IoError>;
function write(p: Path, bytes: Slice<u8>) -> Result<(), IoError>;Write bytes to p, creating or truncating.
function copy(from: Path, to: Path) -> Result<u64, IoError>;
function copy(from: Path, to: Path) -> Result<u64, IoError>;Copy the contents of from to to, returning the number of bytes copied. to is created if missing and truncated if it already exists; the source's Unix permission bits are then applied to it, mirroring cp (and std::fs::copy). from must be a regular file - copying a directory (or other non-regular entry) fails with InvalidInput. On an I/O failure mid-copy the partially written destination is left in place and the error is returned as-is.
Constants
const DEFAULT_CREATE_MODE: u32 = 420;type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct File {
fd: i32;
}File: Read/Write over a file descriptor.
File.fd: i32static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
static File::open(p: Path) -> Result<File, IoError>Open p for reading. Fails with NotFound, PermissionDenied, or a mapped errno-derived kind on failure.
(parameter) p: Pathtype struct Path {
inner: Str;
}Path / PathBuf: filesystem paths as length-typed UTF-8.
std::fs::pathtype struct IoError {
kind: IoErrorKind;
os_code: i32;
}static File::create(p: Path) -> Result<File, IoError>Create (or truncate) p for writing.
static File::open_with(p: Path, options: &OpenOptions) -> Result<File, IoError>(parameter) options: &OpenOptionstype struct OpenOptions {
read: boolean;
write: boolean;
append: boolean;
truncate: boolean;
create: boolean;
create_new: boolean;
}File::seek_set(mut &this, offset: i64) -> Result<u64, IoError>Seek to offset bytes from the start. Returns the new absolute position.
mut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
(parameter) offset: i64File::seek_cur(mut &this, offset: i64) -> Result<u64, IoError>Seek by offset bytes relative to the current position (offset may be negative). Returns the new absolute position.
File::seek_end(mut &this, offset: i64) -> Result<u64, IoError>Seek to offset bytes relative to the end of the file (offset is usually <= 0). Returns the new absolute position.
import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
match (subject) {
Pattern(x) => { ... }
_ => { ... }
}The primary discriminator: branches on enum variants, integers, ranges, and destructuring patterns, and the compiler rejects a match that misses a case. There is no fallthrough. As an expression it evaluates to the chosen arm's value, so every arm must produce the same type.
static File::open(p: Path) -> Result<File, IoError>Open p for reading. Fails with NotFound, PermissionDenied, or a mapped errno-derived kind on failure.
static Path::from(source: Str) -> PathBorrow a Str as a Path. A NUL-terminated string (C-string / i8*) converts implicitly at the call site via Str's ![implicit] new, so Path::from("/tmp") and Path::from(some_str) both work; a C-string's terminating NUL is not part of the path bytes. The borrowed bytes must outlive the Path.
type struct Str {
bytes: u8*;
length: u64;
}Str: a borrowed UTF-8 string slice.
std::collections::strstatic Str::new(text: string) -> StrConstruct from a NUL-terminated C-style string literal. The caller certifies that text is valid UTF-8 and outlives this view. The NUL terminator is not included in the view.
Result::Ok(T)f: Filepattern => { body }Separates a match arm's pattern from its body. Arms do not fall through.
Result::Err(E)e: IoErrortype struct OpenOptions {
read: boolean;
write: boolean;
append: boolean;
truncate: boolean;
create: boolean;
create_new: boolean;
}OpenOptions.read: booleanOpenOptions.write: booleanOpenOptions.append: booleanOpenOptions.truncate: booleanOpenOptions.create: booleanOpenOptions.create_new: booleanstatic OpenOptions::new() -> OpenOptions(parameter) value: booleanOpenOptions::open(&this, p: Path) -> Result<File, IoError>OpenOptions::to_flags(&this) -> i32Flatten the options into the platform open/_open flags bitmask.
mut name: Type = value;A mutable binding, reassignable after declaration - mutability is opt-in, const is the default. At module level it declares mutable global state. Before & it marks an exclusive reference or receiver instead.
mut opts: OpenOptionsstatic OpenOptions::new() -> OpenOptionsmut log: Filemut opts: OpenOptionsOpenOptions::write(mut &this, value: boolean) -> OpenOptionstrueThe boolean literal. Booleans are a distinct 1-byte type, not interchangeable with integers; if and while conditions must be boolean.
OpenOptions::create(mut &this, value: boolean) -> OpenOptionsOpenOptions::append(mut &this, value: boolean) -> OpenOptionsOpenOptions::open(&this, p: Path) -> Result<File, IoError>value?Error propagation. On a Result<T, E> it yields the T of an Ok and otherwise returns the Err(e) from the enclosing function unchanged; on an Option<T> it yields the T of a Some or returns None. The enclosing function must return a matching Result / Option.
const NAME: Type = value;At module level, a true compile-time constant, conventionally SCREAMING_SNAKE_CASE. (mut at module level declares mutable global state instead.)
const DEFAULT_CREATE_MODE: u32 = 420;OpenOptions.create: booleanstatic File::open_with(p: Path, options: &OpenOptions) -> Result<File, IoError>type trait Read {
read(mut &this, buffer: u8*, length: u64) -> Result<u64, IoError>;
read_all(mut &this, buffer: u8*, length: u64) -> Result<u64, IoError>;
read_byte(mut &this) -> Result<Option<u8>, IoError>;
read_char(mut &this) -> Result<Option<u32>, IoError>;
read_until(mut &this, delimiter: u8, out: mut &Array<u8>) -> Result<u64, IoError>;
read_exact(mut &this, buffer: u8*, length: u64) -> Result<(), IoError>;
read_to_end(mut &this, out: mut &Array<u8>) -> Result<u64, IoError>;
read_to_string(mut &this, out: mut &String) -> Result<u64, IoError>;
read_line(mut &this, out: mut &String) -> Result<u64, IoError>;
}type trait Write {
write_some(mut &this, bytes: Slice<u8>) -> Result<u64, IoError>;
flush(mut &this) -> Result<(), IoError>;
write<T>(mut &this, data: T) -> Result<(), IoError>;
}type trait Seek {
seek(mut &this, from: SeekFrom) -> Result<u64, IoError>;
stream_position(mut &this) -> Result<u64, IoError>;
rewind(mut &this) -> Result<(), IoError>;
}A byte stream whose read/write cursor can be repositioned. Absolute positions are u64 offsets from the start; every seek returns the resulting absolute position.
File::seek_set(mut &this, offset: i64) -> Result<u64, IoError>Seek to offset bytes from the start. Returns the new absolute position.
File::seek_cur(mut &this, offset: i64) -> Result<u64, IoError>Seek by offset bytes relative to the current position (offset may be negative). Returns the new absolute position.
File::seek_end(mut &this, offset: i64) -> Result<u64, IoError>Seek to offset bytes relative to the end of the file (offset is usually <= 0). Returns the new absolute position.
File.fd: i32IoErrorKind::NotFoundIoErrorKind::PermissionDeniedOpenOptions::to_flags(&this) -> i32Flatten the options into the platform open/_open flags bitmask.
OpenOptions.read: booleanOpenOptions.write: booleanOpenOptions.append: booleanOpenOptions.truncate: booleanOpenOptions.create_new: booleanimplement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
implement trait Trait for Type { ... }Introduces a trait implementation: the block supplies, for one concrete type, the method bodies the trait requires.
language referenceimplement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language referenceFile::read_to_string(mut &this, out: mut &String) -> Result<u64, IoError>via trait Read
Read every remaining byte into out as UTF-8. Convenience wrapper around read_to_end for the common "slurp text from this source" case. The bytes are **not** validated; the caller certifies the source is UTF-8 (or accepts the consequences of invalid continuation bytes in a String).
function copy(from: Path, to: Path) -> Result<u64, IoError>Copy the contents of from to to, returning the number of bytes copied. to is created if missing and truncated if it already exists; the source's Unix permission bits are then applied to it, mirroring cp (and std::fs::copy).
// reservedA reserved keyword with no syntax of its own in the current grammar. The standard library uses it freely as a method and parameter name (Str::from, from: u64).
IoErrorKind::InvalidInputfunction name<T>(param: Type) -> Ret { ... }Declares a function. Parameters are written name: Type and are never inferred; the return type follows -> and defaults to void. Declaration order does not matter: every signature is collected before any body is checked, so functions may call each other freely and recurse.
function read(p: Path) -> Result<Array<u8>, IoError>Read the entire contents of p into a fresh Array<u8>. Panics on allocation failure; caller handles I/O failure via the Result.
type struct Array<T, A = GlobalAlloc> where A: Allocator {
ptr: T*;
length: i64;
capacity: i64;
alloc: A;
}Array<T, A>: growable, heap-backed, contiguous sequence.
std::collections::arrayfunction read_to_string(p: Path) -> Result<String, IoError>Read the entire contents of p into a fresh String. The bytes are taken verbatim; no UTF-8 validation is performed (the caller is responsible for that if it matters). Panics on allocation failure; I/O failure surfaces through the Result.
type struct String<A = GlobalAlloc> {
buffer: RawBuffer<u8, A>;
length: u64;
}String: owned, heap-allocated, length-typed UTF-8.
std::collections::stringfunction write(p: Path, bytes: Slice<u8>) -> Result<(), IoError>Write bytes to p, creating or truncating.
(parameter) bytes: Slice<u8>type struct Slice<T> {
ptr: T*;
length: u64;
}Slice<T>: a borrowed view into a contiguous sequence.
std::core::sliceprimitive ()The unit type: a value that carries no information, and the empty tuple. Distinct from void, which is the absence of a value - Result<(), E> succeeds with nothing to return. 0 bytes.
function copy(from: Path, to: Path) -> Result<u64, IoError>Copy the contents of from to to, returning the number of bytes copied. to is created if missing and truncated if it already exists; the source's Unix permission bits are then applied to it, mirroring cp (and std::fs::copy).
(parameter) from: Path(parameter) to: Path