Skip to content

Instantly share code, notes, and snippets.

@juliarose
Last active February 13, 2023 18:33
Show Gist options
  • Save juliarose/26dd9e94c356b1b7718bec7bfbc0b2a3 to your computer and use it in GitHub Desktop.
Save juliarose/26dd9e94c356b1b7718bec7bfbc0b2a3 to your computer and use it in GitHub Desktop.
Read/write files in Rust
// https://stackoverflow.com/a/31193386
use std::fs;
use std::io;
fn main() -> Result<(), io::Error> {
// Read a file to a String
let data = fs::read_to_string("/etc/hosts")?;
println!("{}", data);
// Read a file as a Vec<u8>
let data = fs::read("/etc/hosts")?;
println!("{}", data.len());
// Write a file
let data = "Some data!";
fs::write("/tmp/foo", data)?;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment