FAQ - Help and questions

Why does fs::canonicalize return a path starting with \\?\ on Windows?

#paths#windows#canonicalizepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

On Windows, canonicalize returns the extended-length form of the path, which starts with the characters backslash backslash question mark backslash. It is valid, but many programs and string comparisons do not expect it. If you only need an absolute path, use std::path::absolute, which does not touch the file system.

Checked with rustc 1.93.0, Windows 11; compiled and run on Windows only. The behaviour is Windows-specific.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Windows has an extended-length path form, written with the prefix \\?\. It tells the system to use the path as given, which allows paths longer than the traditional limit. Rust's fs::canonicalize returns paths in this form on Windows, and std documents that this is what it does there.

The result is correct but surprising: if you print it, pass it to another program, compare it as text with a path you got elsewhere, or show it to the user, the prefix is in the way.

src/main.rsrust
use std::fs;
use std::path::Path;

fn main() -> std::io::Result<()> {
    let canon = fs::canonicalize(Path::new(r"C:\Windows"))?;
    println!("canonicalize: {}", canon.display());

    // std::path::absolute makes a path absolute without asking the file system and without the verbatim prefix.
    let abs = std::path::absolute(Path::new(r"C:\Windows\System32\..\Fonts"))?;
    println!("absolute:     {}", abs.display());
    println!("exists: {}", abs.exists());
    Ok(())
}
text
canonicalize: \\?\C:\Windows
absolute:     C:\Windows\Fonts
exists: true

Which one to use:

  • You want an absolute path to store or show: std::path::absolute. It does not require the path to exist and does not follow symbolic links. In the run above it also resolved the ...
  • You need the real location, with links followed, and the file must exist: canonicalize. Expect the prefix on Windows, and strip it for display only if you are sure the path is short and has no special parts.
  • You compare two paths for "same file": canonicalize both (so both have the same form), or compare file identity with a crate made for it. Do not compare strings.

Common mistakes#

  • Passing a \\?\ path to a tool that does not understand it. Some programs fail on it.
  • Assuming canonicalize works for a file that does not exist yet. It returns an error; use absolute.

Does this happen on macOS?#

No: the prefix is a Windows form. On macOS canonicalize returns an ordinary absolute path with links resolved (std documentation; not run on a Mac here).

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet