From 2187ac87be12a910696a24732d48bf98858261e2 Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Sat, 9 Oct 2021 14:46:47 +0200 Subject: [PATCH] Add files notes --- Rust/Rust.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Rust/Rust.md b/Rust/Rust.md index 50a2dce..9233c3f 100644 --- a/Rust/Rust.md +++ b/Rust/Rust.md @@ -654,3 +654,33 @@ let v = vec![ Enum::Text("TEST") ]; ``` + +## Files + +### Reading Files + +```rs +use std::fs; + +let contents: Vec = fs::read("path/to/file").unwrap_or_default(); +let contents: String = fs::read_to_string("path/to/file").unwrap_or_default(); + +contents.lines(); // iterator over text lines +``` + +### Writing Files + +```rs +use std::fs; +use std::io::Write; // write trait +// or +use std::io::prelude::*; + +let contents: [u8] = /* */; +let contents = String::from(/* */); + +fs::write("path/to/file", contents); + +let mut file = fs::OpenOptions::new().append(true).open("path/to/file").unwrap(); +file.write(b"appended text"); // write wants an [u8] +```