Rust Program to Get the File Extension


Get the File Extension

Rust Programming Language


Get the File Extension


Problem


Rust program that extracts the file extension from a given filename.

Input


fn get_file_extension(filename: &str) -> Option<&str> {
    match std::path::Path::new(filename).extension() {
        Some(os_str) => os_str.to_str(),
        None => None,
    }
}

fn main() {
    let filename = "example.txt";
    match get_file_extension(filename) {
        Some(extension) => println!("The extension of the file {} is {}", filename, extension),
        None => println!("The file {} does not have an extension.", filename),
    }
}{codeBox}


Output


If you run the above Rust program with the filename variable set to "example.txt", the output will be:

The extension of the file example.txt is txt{codeBox}

assuming that the file "example.txt" exists in the current directory and has a .txt extension. If the file does not have an extension, the output will be:

The file example does not have an extension.{codeBox}


Explanation


This program defines a function get_file_extension that takes a filename as input and returns an Option<&str>, where the Some variant contains the file extension (if it exists), and the None variant is returned if the file does not have an extension.

The get_file_extension function uses the std::path::Path module to get the extension of the file. The function first creates a Path object from the input filename and then calls the extension method on it, which returns an Option<OsStr>. We then use the to_str method to convert the OsStr to a &str and return it as an Option<&str>.

In the main function, we call the get_file_extension function with a filename as input and then use a match expression to print out the result. If the function returns Some(extension), we print out the extension of the file, and if it returns None, we print out a message saying that the file does not have an extension.


Post a Comment