Rust Tutorial
Estimated reading: 3 minutes 33 views

🦀 Rust – Input / Output & File Handling: Read, Write, and Handle Data Safely

🧲 Introduction – Why Learn Input/Output and File Handling in Rust?

Input and output operations are essential for interacting with the real world—whether you’re building a CLI, reading config files, or writing logs. Rust handles I/O using safe abstractions, the powerful std::io module, and the Result type for error management.

🎯 In this guide, you’ll learn:

  • How to perform standard input/output
  • How to read from and write to files
  • How Rust handles I/O errors using Result
  • Examples with full outputs and explanations

💬 Reading User Input (Standard Input)

🔹 Code Example:

use std::io;

fn main() {
    let mut name = String::new();
    println!("Enter your name:");
    io::stdin().read_line(&mut name).expect("Failed to read line");
    println!("Hello, {}!", name.trim());
}

📤 Output:

Enter your name:
John
Hello, John!

🧠 Explanation:

  • String::new() creates a mutable buffer
  • read_line(&mut name) reads into that buffer
  • .trim() removes the newline at the end

📄 Writing to a File

🔹 Code Example:

use std::fs::File;
use std::io::Write;

fn main() {
    let mut file = File::create("output.txt").expect("Failed to create file");
    file.write_all(b"Hello, Rust file!").expect("Failed to write");
}

📤 Output (in output.txt):

Hello, Rust file!

🧠 Explanation:

  • File::create() returns a Result; use .expect() to handle errors
  • write_all() writes bytes to the file

📖 Reading from a File

🔹 Code Example:

use std::fs::File;
use std::io::{self, Read};

fn main() -> io::Result<()> {
    let mut file = File::open("output.txt")?;
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    println!("File content:\n{}", content);
    Ok(())
}

📤 Output:

File content:
Hello, Rust file!

🧠 Explanation:

  • File::open() opens a file for reading
  • read_to_string() reads the content into a String
  • ? propagates errors cleanly

📝 Appending to a File

🔹 Code Example:

use std::fs::OpenOptions;
use std::io::Write;

fn main() {
    let mut file = OpenOptions::new()
        .append(true)
        .open("output.txt")
        .expect("Failed to open file");
    writeln!(file, "\nAppended text").expect("Write failed");
}

📤 Appended Content in File:

Hello, Rust file!
Appended text

🚧 Handling File Errors Gracefully

🔹 Code Example:

use std::fs::File;

fn main() {
    match File::open("nonexistent.txt") {
        Ok(_) => println!("File opened!"),
        Err(e) => println!("Error: {}", e),
    }
}

📤 Output:

Error: No such file or directory (os error 2)

✅ Always handle file I/O using match, unwrap(), or ? with error propagation.


📂 Summary – Recap & Next Steps

Rust’s I/O and file handling system is type-safe, error-aware, and efficient. By using the std::io and std::fs modules, you can read from and write to files safely, with predictable error handling and clean syntax.

🔍 Key Takeaways:

  • Use io::stdin() for reading user input
  • Use File::create() and write_all() to write to files
  • Use File::open() and read_to_string() to read content
  • Use ?, expect(), or match to handle I/O errors gracefully

⚙️ Next: Explore Rust – Smart Pointers & Memory Safety to manage heap allocations and references safely.


❓FAQs


What is the difference between write!() and writeln!() in Rust?
writeln!() adds a newline after writing, while write!() does not.


What does the ? operator do in file I/O?
✅ It automatically returns the error to the caller if the operation fails, simplifying error handling.


How do I check if a file exists in Rust?
✅ Use std::fs::metadata("file.txt").is_ok() or Path::exists() from std::path.


Can I read files line-by-line?
✅ Yes. Use BufReader and .lines() iterator for line-by-line reading.

use std::io::{BufReader, BufRead};
let reader = BufReader::new(File::open("file.txt")?);
for line in reader.lines() {
    println!("{}", line?);
}

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Rust Input / Output & File Handling

Or Copy Link

CONTENTS
Scroll to Top