🐥
Rustでファイルを既定のアプリで開く(Windows限定)
Rust でファイルを既定のファイルで開く(Windows 限定)
Rust を使ってファイルを既定のアプリで開くのに Windows の API を使ってたんですが、もっと単純な方法に気付いたのでメモ。
use std::process::Command;
use std::path::Path;
fn open_file(file_path: &str) -> std::io::Result<()> {
if !Path::new(file_path).exists() {
return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "File not found"));
}
Command::new("cmd")
.args(&["/C", "start", "", file_path])
.spawn()?;
Ok(())
}
fn main() {
match open_file("C:\\path\\to\\your\\file.txt") {
Ok(_) => println!("File opened successfully"),
Err(e) => println!("Error opening file: {}", e),
}
}
以上。
やっていることはコマンドプロンプトで実行させているだけです。
わざわざクレートを使うこともなく実装できるのでお手軽。
Discussion