Post

📁 File IO in #rustlang File system handling is a core building block of using a language effectively, and Rust makes it pretty ergonomic with the std::fs module. Let's take a look at how to use File IO APIs in Rust with a real-world example: a grade manager for students and courses 🧵👇

0️⃣ Creating files Let's start by creating a file. You can see that File::create is used to create a file, if the file already exists it will be truncated. The file is opened in write-only mode and the API returns a result which makes error handling explicit.

1️⃣ Writing to the file with writeln! Let's improve the error handling and handle the Result and write some data to the file. Notice the use of `ref mut` to get a mutable reference to the file inside the match arm and that the writeln! macro also returns a Result which we handle with expect.

0 reposts0 likes

2️⃣ Writing to the file with fs::write We can also use fs::write to write to the file, which is a bit more concise for small files. the write call will both open the file, write to it, and then close the file. Pretty neat!

3️⃣ Reading to string We can use fs::read_to_string to read the entire contents of a file into a string. This is super handy for small files. Again, we handle the Result to manage errors gracefully.

4️⃣ Creating directories Another common task is creating directories. You can use fs::create_dir_all to create a directory and all its parent components if they are missing.

5️⃣ Parsing contents into structured data Technically not part of the std::fs API but another common pattern is to read a file and then parse its contents into a structured format. Here's how we can read back the grades file. We could also use JSON/CSV+real parser, this is just a simple example.