Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
:timing
:sccache 1
Tips and Traps¶
Use buffered IO as much as possible (for performance concerns). However, be aware that
BufWriter
might not write data into a file untilBufWriter.flush
is called. This is especially tricky if you explore Rust code in a JupyterLab notebook. If you useBufWriter
in a JupyterLab notebook, it is suggested that you either callBufWriter.flush
manually:::Rust let f = File::create("stat.csv").expect("Unable to create file"); let mut bfw = BufWriter::new(f); for (id, n, num_jokers, rank, htype) in &stat { bfw.write(format!("{id},{n},{num_jokers},{rank},{htype}\n").as_bytes()); } bfw.flush()
or you enclose
BufWriter
in a smaller curly brace scope (to rely on the Drop check to trigger flush).:::Rust { let f = File::create("stat.csv").expect("Unable to create file"); let mut bfw = BufWriter::new(f); for (id, n, num_jokers, rank, htype) in &stat { bfw.write(format!("{id},{n},{num_jokers},{rank},{htype}\n").as_bytes()); } }
Key strokes
CTRL
+D
signals an EOF to stdin input.Methods reading from stdin appends the input to the buffer rather than overwrite it!
Rust crates serde and cron are popular serialization/deserialization libraries.
use std::path::Path;
use std::io::BufReader;
use std::fs::File;
use std::io::Read;
use std::io::Lines;
use std::io::{self, BufReader, BufWriter};
use std::io::prelude::*;
use std::fs::File;
use std::fs;
fs::read_to_string("data.txt")
std::fs::read¶
Read the entire contents of a file into a bytes vector.
This is a convenience function for using File::open
and read_to_end
with fewer imports and without an intermediate variable.
It pre-allocates a buffer based on the file size when available,
so it is generally faster than reading into a vector created with Vec::new()
.
fs::read("data.txt")
fs::write("o1.txt", "this is an example line output")
std::fs::File¶
You can open a file from both a Path and a string.
let f1 = File::open(Path::new("data.txt"));
f1
let f2 = File::open("data.txt");
f2
Read text from a file.
let mut f = File::open("data.txt")?;
let mut content = String::new();
f.read_to_string(&mut content)?;
content
Write text into a file.
let mut file = File::create("output.txt").unwrap();
file
file.write_all(b"Hello, world!");
std::io::BufReader¶
let br = BufReader::new(File::open("data.txt")?);
for line in br.lines() {
println!("{:?}", line);
}
let br = BufReader::new(File::open("data.txt")?);
for (idx, line) in br.lines().enumerate() {
println!("Line {}: {:?}", idx, line);
}
let br = BufReader::new(File::open("data.txt")?);
for (idx, line) in br.lines().enumerate() {
println!("Line {}: {:?}", idx, line);
}
std::io::BufWriter¶
let f = File::create("o2.txt").expect("Unable to create file");
let mut bfw = BufWriter::new(f);
bfw.write_all(b"writing data\nusing std::io::BufWriter")
You have to call the method BufWriter.flush
to force the buffer to output immediately.
bfw.flush()
Before a buffer is destructed, its content is output to the file.
{
let f = File::create("o3.txt").expect("Unable to create file");
let mut bfw = BufWriter::new(f);
bfw.write_all(b"writing data\nusing std::io::BufWriter")
}
Read From Stdin¶
Stdin::read_line reads a line (terminated by \n
)
and returns a Result object.
On success,
it returns Ok(n)
where n
is the number of bytes read from stdin.
let mut buffer = String::new();
let stdin = std::io::stdin();
let r = stdin.read_line(&mut buffer);
Read/Write CSV in Rust¶
Please refer to Read and Write CSV Files in Rust for details.
Bundle File into Rust Application¶
Please refer to Bundle Resource Files into a Rust Application for more discussions.
fs::canonicalize("./o1.txt")
fs::copy("o1.txt", "out1.txt")
fs::create_dir("my_dir")
fs::create_dir_all("another/dir")
fs::metadata("o1.txt")
fs::read_dir(".")
for file in fs::read_dir(".").unwrap() {
println!("{:?}", file);
}
fs::read_link("out2.txt")
fs::remove_dir¶
Removes an empty directory.
fs::remove_dir("another")
fs::remove_dir("my_dir")
fs::remove_dir_all("another")
https://doc.rust-lang.org/std/fs/fn.remove_file.html
https://doc.rust-lang.org/std/fs/fn.rename.html