Rust:- File I/O – Read File

Background

Let us go over the steps to read a text file in Rust.

Code

Outline

Cargo.toml

  1. Dependencies
    • [dependencies]
      exitcode = “1.1.2”

 

Code Block

  1. Import Modules
    • Command Line Arguments
      • use std::env;
    • File System – File I/O
      • use std::fs;
  2. Declare Constants
    • const COMMAND_LINE_ARGUMENT_COUNT: usize =2;
    • const COMMAND_LINE_ARGUMENT_POSITION_FILENAME:usize=1;
  3. Declare Variables
    • let arguments_cmdline: Vec<String>;
    • let arguments_cmdline_length: usize;
    • let filename:&str;
    • let file_contents:String;
  4. Processing
    • Store Command Line Arguments
      • arguments_cmdline = env::args().collect();
    • Get Number of Command Line Arguments
      • arguments_cmdline_length = arguments_cmdline.len();
    • Sanitize Command Line Arguments
      • If Number of Command Line Arguments does not match expectations, exit application
        • std::process::exit(exitcode::USAGE);
    • Get Command Line Arguments
      • Get Filename
        • filename = &arguments_cmdline[1];
    • Get File Contents
      • file_contents = fs::read_to_string(filename)
    • Display File Contents
      • println!( “{0}”, file_contents );

 

Source Code

 

cargo.toml


[package]

#warning: crate `fsTextRead` should have a snake case name
#help: convert the identifier to snake case: `fs_text_read`
#note: `#[warn(non_snake_case)]` on by default
#name = "fsTextRead"
name = "fstextread"

version = "0.1.0"

edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
exitcode = "1.1.2"

Code Source


//Command Line Arguments
use std::env;

//File System -  File I/O
use std::fs;

fn main()
{
        
    /*
        Define Constants 
    */
    const COMMAND_LINE_ARGUMENT_COUNT: usize =2;
    
    const COMMAND_LINE_ARGUMENT_POSITION_FILENAME:usize=1;
    
    
    /*
        Declare Variables
    */
    //command line arguments
    let arguments_cmdline: Vec<String>;
    
    //command line arguments length
    let arguments_cmdline_length: usize;
    
    //filename
    let filename:&str;
    
    //file contents
    let file_contents:String;

    /*
        Get Command line arguments
    */  
    arguments_cmdline = env::args().collect();
        
    /*
        Pass arguments to debugger
    */
    //dbg!(arguments_cmdline);  
    
    /*
        Get Number of Command Line Arguments
    */
    arguments_cmdline_length = arguments_cmdline.len();
    
    /*
        If number of arguments does not meet expectations, exit
    */
    if arguments_cmdline_length != COMMAND_LINE_ARGUMENT_COUNT
    {
        
        /*
            Unexpected Number of Command Line Arguments
        */
        println!(
                      "Unexpected Number of command line arguments {0}.  Expected <filename>."
                    , arguments_cmdline_length
                );          
        
        /*
            Installing from crates.io
            https://crates.io/crates/exitcode
        */
        std::process::exit(exitcode::USAGE);        
        
    }
    
    /*
        Get Command Line Parameters
        
            Argument 1:- Filename
    */
    filename = &arguments_cmdline[COMMAND_LINE_ARGUMENT_POSITION_FILENAME];
    

    // print separator
    println!(""); 
            
    // Print Filename
    println!(
                  "Filename {0}"
                , filename
            );     


    // print separator
    println!("");  
    
    /*
        Read file
    */
    file_contents = fs::read_to_string(filename)
        .expect("Should have been able to read the file");
        

    // Print File Contents Header
    println!( "File Contents" );   
            
    // Print File Contents Header Separator
    println!( "------------" );   
                        
    // Print File Contents
    println!( "{0}", file_contents );   
            

}



Code Sharing

  1. GitLab

 

References

  1. Modules
    • module:std::env
      Link
    • module::std::fs
      Link
    • module:st::process
      Link
  2. Method
    • std::fsread_to_string
      Link

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s