Reading and writing files
Read project files with fs::read_to_string, return io::Result from main, and write temporary files under /tmp.
Runs in Zerethon IDE · Rust 1.87
Official Rust documentation ↗
A run sees the project's files in its working folder, read-only. A program may write files under /tmp; they are deleted when the run ends.
main.rs
use std::fs;
fn main() -> std::io::Result<()> {
let text = fs::read_to_string("data.csv")?;
let mut count = 0;
for line in text.lines().skip(1) {
let fields: Vec<&str> = line.split(',').collect();
println!("{} {}", fields[0], fields[1]);
count += 1;
}
fs::write("/tmp/report.txt", format!("count={count}\n"))?;
print!("{}", fs::read_to_string("/tmp/report.txt")?);
Ok(())
}
data.csv
name,score
ada,90
alan,85
Output
ada 90 alan 85 count=2
mainmay returnstd::io::Result<()>; then?works inside it, and an error ends the program with a message.- Paths are relative to the project root:
fs::read_to_string("data/input.txt")reads the file shown in the explorer asdata/input.txt. - Writing next to your code fails with
Read-only file system— use/tmp/out.txt. - There is no
csvorserdecrate; split simple CSV lines yourself as above.