Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

** Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement! **

Tips and Traps

  1. Use buffered IO as much as possible (for performance concerns). However, be aware that BufWriter might not write data into a file until BufWriter.flush is called. This is especially tricky if you explore Rust code in a JupyterLab notebook. If you use BufWriter in a JupyterLab notebook, it is suggested that you either call BufWriter.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());
       }
     }
  2. Key strokes CTRL + D signals an EOF to stdin input.

  3. Methods reading from stdin appends the input to the buffer rather than overwrite it!

  4. Rust crates serde and cron are popular serialization/deserialization libraries.

Err(Os { code: 2, kind: NotFound, message: "No such file or directory" })

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().

Ok([104, 111, 119, 10, 97, 114, 101, 32, 121, 111, 117, 10, 100, 111, 105, 110, 103])
Ok(())

std::fs::File

You can open a file from both a Path and a string.

Ok(File { fd: 3, path: "/workdir/archives/blog/misc/content/2020/11/rust-io/data.txt", read: true, write: false })
Ok(File { fd: 4, path: "/workdir/archives/blog/misc/content/2020/11/rust-io/data.txt", read: true, write: false })

Read text from a file.

"how\nare you\ndoing"

Write text into a file.

File { fd: 4, path: "/workdir/archives/blog/misc/content/2020/11/rust-io/output.txt", read: false, write: true }

std::io::BufReader

Ok("how")
Ok("")
Ok("are you")
Ok("doing")
()
Line 0: Ok("how")
Line 1: Ok("")
Line 2: Ok("are you")
Line 3: Ok("doing")
()
Line 0: Ok("how")
Line 1: Ok("")
Line 2: Ok("are you")
Line 3: Ok("doing")
()

std::io::BufWriter

Ok(())

You have to call the method BufWriter.flush to force the buffer to output immediately.

Ok(())

Before a buffer is destructed, its content is output to the file.

Ok(())

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.

!pwd
 ^^^ not found in this scope
cannot find value `pwd` in this scope

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.

Ok("/workdir/archives/blog/misc/content/2020/11/rust-io/o1.txt")
Ok(30)
Ok(())
Ok(())
Ok(Metadata { file_type: FileType(FileType { mode: 33188 }), is_dir: false, is_file: true, permissions: Permissions(FilePermissions { mode: 33188 }), modified: Ok(SystemTime { tv_sec: 1627506651, tv_nsec: 611396728 }), accessed: Ok(SystemTime { tv_sec: 1627506651, tv_nsec: 987468906 }), created: Err(Error { kind: Other, message: "creation time is not available for the filesystem" }), .. })
Ok(ReadDir("."))
Ok(DirEntry("./.ipynb_checkpoints"))
Ok(DirEntry("./another"))
Ok(DirEntry("./my_dir"))
Ok(DirEntry("./o1.txt"))
Ok(DirEntry("./o2.txt"))
Ok(DirEntry("./o3.txt"))
Ok(DirEntry("./out1.txt"))
Ok(DirEntry("./output.txt"))
Ok(DirEntry("./rust-io.ipynb"))
()
Ok("o2.txt")

fs::remove_dir

Removes an empty directory.

Err(Os { code: 39, kind: Other, message: "Directory not empty" })
Ok(())
Ok(())