Skip to content

Instantly share code, notes, and snippets.

@Geal
Created May 7, 2021 12:58
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 Geal/3d0e8770d4caaf2f49406085eaf28fc6 to your computer and use it in GitHub Desktop.
Save Geal/3d0e8770d4caaf2f49406085eaf28fc6 to your computer and use it in GitHub Desktop.
use std::{
fs::File,
str::from_utf8,
io::{Read, Write},
os::unix::io::AsRawFd,
};
fn main() -> std::io::Result<()> {
let mut write_file = File::create("test.txt")?;
let mut read_file = File::open("test.txt")?;
assert_ne!(write_file.as_raw_fd(), read_file.as_raw_fd());
write_file.write_all(b"ABCDEFGHIJKL")?;
println!("wrote to file");
loop {
let mut buffer = [0u8; 4];
let sz = read_file.read(&mut buffer)?;
if sz > 0 {
println!("read() returned {} bytes: {:?}", sz, from_utf8(&buffer[..sz]));
} else {
println!("read() returned 0, we're at end of file");
break;
}
}
write_file.write_all(b"MNOPQRSTUVWXYZ")?;
println!("wrote more data to the file");
loop {
let mut buffer = [0u8; 4];
let sz = read_file.read(&mut buffer)?;
if sz > 0 {
println!("read() returned {} bytes: {:?}", sz, from_utf8(&buffer[..sz]));
} else {
println!("read() returned 0, we're at end of file");
break;
}
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment