2

I'm trying to canonicalize a simple path containing the home directory ~ in Rust:

use std::path::PathBuf;

fn main() {
  let path_str = "~"; // fails
  // let path_str = ".."; // works
  let path_buf = PathBuf::from(path_str);
  let canon = path_buf.canonicalize().unwrap();
  println!("{:?}", canon);
}

In my actual program, the ~ path comes from user input. This program fails on the .canonicalize().unwrap(), giving Os { code: 2, kind: NotFound, message: "No such file or directory" }.

Is it a bug or a feature that Rust fails to canonicalize the ~? What should I be doing instead?

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
mwlon
  • 798
  • 5
  • 19
  • I would say that this is for cross-compatibility reasons, as IIRC `~` is Unix specific, so I feel that you should use a Unix specific mechanism to expand it. Maybe [this](https://stackoverflow.com/questions/54267608/expand-tilde-in-rust-path-idiomatically) can help? – jthulhu May 16 '22 at 17:23
  • All the `fs` stuff is OS-specific to begin with, right? It has different logic for Windows vs Unix, so I don't think that's the reason. – mwlon May 16 '22 at 17:32
  • 3
    Keep in mind that tilde expansion is a *shell* feature, and has nothing to do with the underlying file system. You are under no obligation to support it. `..`, on the other hand, *is* an actual file system entry (where available), not a shell shortcut. – chepner May 16 '22 at 19:28

0 Answers0