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 fnNotes:
- 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 fnNotes:
- Creates parent directories if they don't exist
- Completely overwrites existing file content
- Returns
Uniton 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 fnNotes:
- Returns
trueif the file exists and is readable - Returns
falseif 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 fnNotes:
- 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 fnFunction Summary ​
| Function | Signature | Description |
|---|---|---|
read_file | String -> String | Read file contents |
write_file | (String, String) -> Unit | Write string to file |
file_exists | String -> Bool | Check if file exists |
get_env | String -> String | Get environment variable |
See Also ​
- Types & Conversions - String operations for processing file content
- Lists - Working with lines and data
- Quantum Operations - Quantum computing functions