乐闻世界logo
搜索文章和话题

How to get file path without extension in Rust?

1个答案

1

In Rust, when working with file paths, we typically use the std::path::Path and std::path::PathBuf types. They provide a comprehensive set of methods for manipulating various components of a path.

To obtain the filename without its extension, we can use the with_extension method of Path by passing an empty string as a parameter to remove the extension. However, this method is primarily intended for replacing the extension, not removing it. Instead, to directly retrieve the path without the extension, we should use the file_stem method.

Here is a simple example demonstrating how to implement this:

rust
use std::path::Path; fn main() { // Assume a file path let path = Path::new("/tmp/filename.rs"); // Use `file_stem` to get the filename without extension let stem = path.file_stem().and_then(|s| s.to_str()); if let Some(s) = stem { println!("File stem: {}", s); } else { println!("No stem found!"); } }

In this example:

  1. We create a Path instance representing a specific file path.
  2. Using the file_stem method to obtain the filename component without its extension. This method returns an Option<&OsStr> result, which may be None if the path lacks an extension or stem.
  3. Using and_then and to_str to convert the OsStr to a &str for easier handling and display.
  4. Finally, we use the if let construct to check the result. If the filename is successfully retrieved, it is printed; otherwise, an error message is displayed.

This example demonstrates how to safely and effectively handle file paths and filenames in Rust. Using Path and related methods helps avoid common pitfalls and makes the code more robust and readable.

2024年7月17日 19:42 回复

你的答案