DEV Community 👩‍💻👨‍💻


Posted on

Day18:File Operation - 100DayOfRust

File operation: read, write and append.


use std::fs;
use std::io::prelude::*;

fn main() {
    // write file
    let age = 12;
    let mut f = fs::File::create("newfile").unwrap();
    // 1st way: write_all
    f.write_all(b"some content here\n").unwrap();
    // 2nd way: write!
    write!(f, "age: {}\n", age).unwrap();
    // 3rd way: fs::write
    fs::write("sample.txt", "sample code").unwrap();

    // read file
    let mut fread = fs::File::open("newfile").unwrap();
    let mut content = String::new();
    // 1st way: File.read_to_string
    fread.read_to_string(&mut content).unwrap();
    println!("File content(1):\n{}", content);
    // 2nd way: fs::read_to_string
    let fcontent = fs::read_to_string("newfile").unwrap();
    println!("File content(2):\n{}", fcontent);

    // append mode
    // Use OpenOptions to open file in append mode
    let mut fappend = fs::OpenOptions::new()
    write!(fappend, "append one line\n").unwrap();

    let fcontent = fs::read_to_string("newfile").unwrap();
    println!("File content(3):\n{}", fcontent);
Enter fullscreen mode Exit fullscreen mode


File content(1):
some content here
age: 12

File content(2):
some content here
age: 12

File content(3):
some content here
age: 12
append one line

Enter fullscreen mode Exit fullscreen mode


Top comments (0)

Update Your DEV Experience Level:


Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠