Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. use std::io::prelude::*;
  2. use std::io;
  3. use std::fs::File;
  4. use std::convert::TryInto;
  5. use std::error::Error;
  6.  
  7. fn main() -> Result<(), Box<dyn Error>> {
  8. let test_strings = [
  9. "hello",
  10. "my name is \n",
  11. "rust",
  12. "fearless concurrency!",
  13. ];
  14.  
  15. let file_name = "test.txt";
  16. {
  17. let mut file = File::create(file_name)?;
  18. for &string in &test_strings {
  19. let string_len: u16 = string.len().try_into()?;
  20. file.write_all(&string_len.to_le_bytes())?;
  21. file.write_all(string.as_bytes())?;
  22. }
  23. }
  24.  
  25. {
  26. let mut buf = vec![];
  27. let mut file = File::open(file_name)?;
  28. loop {
  29. let mut len_buf = [0u8; 2];
  30. match file.read_exact(&mut len_buf) {
  31. Ok(()) => (),
  32. Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof => break,
  33. Err(e) => return Err(e.into()),
  34. }
  35. let len = u16::from_le_bytes(len_buf) as usize;
  36. buf.resize(len, 0);
  37. file.read_exact(&mut buf)?;
  38. let string = String::from_utf8_lossy(&buf);
  39. println!("{}", string);
  40. }
  41. }
  42.  
  43. Ok(())
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement