Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::io::prelude::*;
- use std::io;
- use std::fs::File;
- use std::convert::TryInto;
- use std::error::Error;
- fn main() -> Result<(), Box<dyn Error>> {
- let test_strings = [
- "hello",
- "my name is \n",
- "rust",
- "fearless concurrency!",
- ];
- let file_name = "test.txt";
- {
- let mut file = File::create(file_name)?;
- for &string in &test_strings {
- let string_len: u16 = string.len().try_into()?;
- file.write_all(&string_len.to_le_bytes())?;
- file.write_all(string.as_bytes())?;
- }
- }
- {
- let mut buf = vec![];
- let mut file = File::open(file_name)?;
- loop {
- let mut len_buf = [0u8; 2];
- match file.read_exact(&mut len_buf) {
- Ok(()) => (),
- Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof => break,
- Err(e) => return Err(e.into()),
- }
- let len = u16::from_le_bytes(len_buf) as usize;
- buf.resize(len, 0);
- file.read_exact(&mut buf)?;
- let string = String::from_utf8_lossy(&buf);
- println!("{}", string);
- }
- }
- Ok(())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement