std/fs
The std/fs module provides file and directory operations.
Import
Section titled “Import”import "std/fs";FileInfo
Section titled “FileInfo”type FileInfo struct { .path: str, .size: i64, .isDir: bool, .isFile: bool, .exists: bool};type File struct { .handle: __file, .path: str, .mode: str};File is a resource handle type:
- Non-copyable
- Value passing/assignment moves ownership
Close()uses a value receiver and consumes the handle
FileMode
Section titled “FileMode”type FileMode enum { Read, Write, Append, ReadWrite, CreateRW, AppendRead};SeekWhence
Section titled “SeekWhence”type SeekWhence enum { Start, Current, End};Core API
Section titled “Core API”fn ReadFile(path: str) -> str ! strfn WriteFile(path: str, content: str) -> str ! boolfn AppendFile(path: str, content: str) -> str ! bool
fn Exists(path: str) -> boolfn Stat(path: str) -> str ! FileInfofn Size(path: str) -> str ! i64
fn Open(path: str, mode: FileMode) -> str ! Filefn Create(path: str) -> str ! Filefn CreateRW(path: str) -> str ! Filefn OpenAppend(path: str) -> str ! File
fn (f: File) Close()fn (f: &mut File) ReadLine() -> str ! strfn (f: &mut File) ReadBytes(maxBytes: i32) -> str ! []bytefn (f: &mut File) Read(maxBytes: i32) -> str ! []bytefn (f: &mut File) WriteStr(content: str) -> str ! boolfn (f: &mut File) WriteLine(content: str) -> str ! boolfn (f: &mut File) Write(buf: []byte) -> str ! i32fn (f: &mut File) Seek(offset: i64, whence: SeekWhence) -> str ! i64fn (f: &mut File) Rewind() -> str ! i64
fn Remove(path: str) -> str ! boolfn Mkdir(path: str) -> str ! boolfn Rmdir(path: str) -> str ! bool
fn Cwd() -> str ! strfn Join(base: str, path: str) -> strfn Ext(path: str) -> strfn Base(path: str) -> strfn Dir(path: str) -> strExample: Read/Write + Seek
Section titled “Example: Read/Write + Seek”import "std/fs";import "std/io";
fn main() { let file := fs::CreateRW("demo.txt") catch err { io::Println("create error:", err); return; };
defer file.Close();
file.WriteStr("Hello\nWorld\n") catch err { io::Println("write error:", err); return; };
file.Rewind() catch err { io::Println("rewind error:", err); return; };
let line1 := file.ReadLine() catch err { io::Println("read error:", err); return; };
io::Println("first line:", line1);}Ownership Notes
Section titled “Ownership Notes”let f1 := fs::Create("a.txt") catch err { return; };let f2 := f1; // ownership moved to f2// f1.Close(); // ❌ use of moved valuef2.Close();Use &File / &mut File in helper APIs when the caller should retain ownership.