Chapter 12: An I/O Project - Building a CLI Program
In this chapter, we'll build a practical command-line program that demonstrates several concepts we've learned: file I/O, handling command-line arguments, error handling with the ? operator, and testing. We'll create a grep-like tool called oxgrep that searches for a query string in a file and prints matching lines.
Project Overview
Our oxgrep program will:
- Accept a search query and a filename as command-line arguments
- Read the file
- Find and print lines containing the query
- Handle errors gracefully with custom error types and the
?operator - Include comprehensive tests
This is an excellent opportunity to practice:
- Command-line argument parsing - Processing user input
- File I/O - Reading files efficiently
- Error handling - Creating custom error types and using the
?operator - Code organization - Separating concerns into modules
- Testing - Writing tests for different scenarios
- Refactoring - Improving code quality and maintainability
Getting Started
Let's create a new binary project:
cargo new oxgrep
cd oxgrep
This creates a project with the following structure:
oxgrep/
├── Cargo.toml
└── src/
└── main.ox
Throughout this chapter, we'll build up the program incrementally, explaining each piece as we go. We'll start with the simplest working version and then add features and improve the design.
What We'll Build
By the end of this chapter, you'll have a working program that can be used like this:
cargo run -- to sample.txt
cargo run -- is poem.txt
cargo run -- CASE_INSENSITIVE sample.txt -- -i
The program will output matching lines and handle missing files, invalid arguments, and other error conditions gracefully.
Let's dive in!
Next Steps
- Accepting Command Line Arguments - Parse user input
- Reading a File - Learn how to work with the file system
- Refactoring to Improve Modularity and Error Handling - Build better error handling
- Adding Functionality with Test Driven Development - Ensure your code works correctly
- Working with Environment Variables - Handle case-insensitive search
- Redirecting Errors to Standard Error - Keep stdout clean
- Improving Our I/O Project (Chapter 13) - Polish your implementation