How to read file in RUST

This post explains how to read a file in Rust language.

For following below instructions rust and VsCode installation is required, if you don't have rust installed, follow link install rust on windows.

Code snippet for reading a file in Rust
  
    use std::fs;

    fn main() {

        println!("file contains {}", "sample.txt");

        let filedata = fs::read_to_string("sample.txt")
            .expect("Something went wrong ");

        println!("content of file sample data:\n{}", filedata);
    }
  
  
Explanation
  • Above code snippet will print contents of file named "sample.txt"
  • use std::fs; brings standard library component to handle files
  • fn main() is declaring new function
  • fs::read_to_string("sample.txt") is reading contents of file and storing in variable filedata
  • .expect sets custom messages for any possible errors
  • Compile and Run the Rust program.
    
    
    E:\rust-tutorials\rust-scripts>rustc main.rs
    
    E:\rust-tutorials\rust-scripts>.\main.exe
    
    #### Output ####
    file contains sample.txt
    content of file sample data:
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed est turpis, fringilla ac aliquam id,
    sodales eu tellus. Nullam tellus mi, scelerisque at massa id, blandit euismod nisi.
    Proin mollis volutpat magna non mattis. Ut a lorem felis. Morbi ac porta metus,
    non varius mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus.
    Cras ac nibh vel sapien feugiat laoreet a at nunc. Nunc nec metus tincidunt, bibendum tortor id,
    imperdiet mauris. Vivamus luctus, magna vel fringilla pellentesque,
    dolor sapien ornare tortor, sed aliquet leo turpis eu purus. Vivamus varius viverra consequat.
    
    
    

    Follow US on Twitter: