Skip to content

Instantly share code, notes, and snippets.

@max-itzpapalotl
Last active February 25, 2024 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max-itzpapalotl/7225b1a3605c6a9669700f25cad43202 to your computer and use it in GitHub Desktop.
Save max-itzpapalotl/7225b1a3605c6a9669700f25cad43202 to your computer and use it in GitHub Desktop.
17. File I/O

17. File I/O

Low level unbuffered I/O

The fs module is for file system access and has the File struct, the io module contains traits and code for performing I/O, the most fundamental ones are the Read and Write and Seek traits.

use std::fs;
use std::fs::File;
use std::io::{Read, Write, Seek, SeekFrom};

fn main() {
    let data_orig = b"abcdefghijklmnopqrstuvwxyz";
    fs::write("file.txt", data_orig).unwrap();
    println!("Have written file 'file.txt'.");

    let data = fs::read_to_string("file.txt").unwrap();
    println!("Data read: {data}");

    {
        let mut file = File::create("file2.txt").unwrap();
        let size = file.write(data_orig).unwrap();
        file.flush().unwrap();
        println!("Wrote {size} bytes!");
    }

    {
        let mut file = File::open("file2.txt").unwrap();
        let mut v = [0u8; 1024];
        let size = file.read(&mut v).unwrap();
        println!("Size read: {} Data:\n{:?}", size, &v[0..size]);
    }

    {
        let mut file = File::open("file2.txt").unwrap();
        file.seek(SeekFrom::Start(13)).unwrap();
        let mut v = [0u8; 1024];
        let size = file.read(&mut v).unwrap();
        println!("Size read: {} Data:\n{:?}", size, &v[0..size]);
    }
}

Buffered I/O

The io modules contains the BufRead trait and the BufReader and BufWriter, classes, which can wrap readers and writers.

use std::fs::File;
use std::io::{Read, Write, BufRead, BufReader, BufWriter};

fn main() {
    {
        let s = b"abcdef\nghijklmnopq\nrstuvwxyz";
        let f = File::create("file.txt").unwrap();
        let mut bf = BufWriter::with_capacity(100, f);
        for i in 0..s.len() {
            bf.write(&s[i..i+1]).unwrap();
        }
        bf.flush().unwrap();
        println!("Have written a file with {} bytes.", s.len());
    }

    {
        let f = File::open("file.txt").unwrap();
        let mut bf = BufReader::with_capacity(100, f);
        let mut buf : Vec<u8> = Vec::with_capacity(100);
        loop {
            let mut minibuf = [0u8; 1];
            let r = bf.read(&mut minibuf).unwrap();
            if r == 0 {
                break;
            }
            buf.push(minibuf[0]);
        }
    }

    {
        let f = File::open("file.txt").unwrap();
        let bf = BufReader::with_capacity(100, f);
        for l in bf.lines() {
            let line = l.unwrap();
            println!("Read line: {line}");
        }
    }
}

Stdin and more about the BufRead trait

use std::io::{stdin, BufRead};

fn main() {
    let mut sin = stdin().lock();
    let mut line = String::with_capacity(100);
    loop {
        line.clear();
        let size = sin.read_line(&mut line).unwrap();
        if size == 0 {
            break;
        }
        println!("You have written this: {}", line);
    }
}

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment