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]);
}
}
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}");
}
}
}
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);
}
}
- Rust by example: https://doc.rust-lang.org/rust-by-example/std_misc/file.html
- The
Read
trait: https://doc.rust-lang.org/std/io/trait.Read.html - The
Write
trait: https://doc.rust-lang.org/std/io/trait.Write.html - The
Seek
trait: https://doc.rust-lang.org/std/io/trait.Seek.html - The
BufRead
trait: https://doc.rust-lang.org/std/io/trait.BufRead.html - The
File
struct: https://doc.rust-lang.org/stable/std/fs/struct.File.html - The
BufReader
struct: https://doc.rust-lang.org/std/io/struct.BufReader.html - The
BufWriter
struct: https://doc.rust-lang.org/std/io/struct.BufWriter.html - Video: https://youtu.be/PkLnsLDT6gc
- Overview: https://gist.github.com/max-itzpapalotl/18f7675a60f6f9603250367bcb63992e