Skip to content

I/O & Environment ​

Functions for file operations and environment variable access.

File Operations ​

read_file ​

Signature: read_file(path: String) -> String

Reads the entire contents of a file as a string.

kettle
fn main() -> Unit using file_io
  content = read_file("example.txt")
  print(content)
end fn

Notes:

  • The path can be absolute or relative to the current working directory
  • Throws an error if the file does not exist or cannot be read
  • Returns the entire file content as a single string

write_file ​

Signature: write_file(path: String, content: String) -> Unit

Writes a string to a file, creating the file if it doesn't exist or overwriting if it does.

kettle
fn main() -> Unit using file_io
  write_file("output.txt", "Hello, Kettle!")
  print("File written")
end fn

Notes:

  • Creates parent directories if they don't exist
  • Completely overwrites existing file content
  • Returns Unit on success, throws error on failure

file_exists ​

Signature: file_exists(path: String) -> Bool

Checks whether a file exists at the given path.

kettle
fn main() -> Unit using file_io
  match file_exists("config.json")
    True -> print("Config found")
    False -> print("No config")
  end match
end fn

Notes:

  • Returns true if the file exists and is readable
  • Returns false if the file doesn't exist or is not accessible

Environment ​

get_env ​

Signature: get_env(name: String) -> String

Retrieves the value of an environment variable.

kettle
fn main() -> Unit using file_io
  home = get_env("HOME")
  print("Home: \${home}")
end fn

Notes:

  • Returns an empty string if the variable is not set
  • Variable names are case-sensitive on Unix systems

Common Patterns ​

Copying Files ​

Processing File Lines ​

Configuration with Fallback ​

Error Handling ​

File operations can fail for various reasons (file not found, permission denied, etc.). Currently, these operations will cause a runtime error. For safer handling:

kettle
fn safe_read(path: String) -> Option[String] with IO
  match file_exists(path)
    True -> Some(read_file(path))
    False -> None
  end match
end fn

fn main() -> Unit using file_io
  match safe_read("maybe.txt")
    Some(content) -> print(content)
    None -> print("File not found")
  end match
end fn

Function Summary ​

FunctionSignatureDescription
read_fileString -> StringRead file contents
write_file(String, String) -> UnitWrite string to file
file_existsString -> BoolCheck if file exists
get_envString -> StringGet environment variable

See Also ​