FAQ - Help and questions

How do I build file paths that work on both Windows and macOS?

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

Short answer

Never join paths with string formatting. Use Path and PathBuf: push or join each part, and read the pieces back with file_name, extension, parent and components. The program uses the system's separator, backslash on Windows and slash on macOS. A join with an absolute path replaces everything before it.

Checked with rustc 1.93.0, Windows 11; compiled and run. The output shows the Windows separator; on macOS the same program prints forward slashes (std documents this; not run on a Mac).

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

#1

Answer#

Windows separates path parts with \ and macOS with /. Instead of gluing strings together (format!("{dir}/{name}")), use PathBuf, which knows the rules of the system the program is compiled for.

src/main.rsrust
use std::path::{Path, PathBuf};

fn main() {
    let mut p = PathBuf::from("projects");
    p.push("demo");
    p.push("notes.txt");
    println!("{}", p.display()); // the separator is the running system's own
    println!("file_name: {:?}", p.file_name().unwrap());
    println!("extension: {:?}", p.extension().unwrap());
    println!("parent:    {:?}", p.parent().unwrap());
    println!("with_extension: {}", p.with_extension("md").display());

    // join() with an absolute path REPLACES what came before it:
    let base = Path::new("data");
    println!("{}", base.join("a.txt").display());
    println!("{}", base.join("C:\\other\\a.txt").display());

    // Components are the portable way to walk a path:
    for c in Path::new("a/b/../c.txt").components() {
        print!("{c:?} ");
    }
    println!();
}
text
projects\demo\notes.txt
file_name: "notes.txt"
extension: "txt"
parent:    "projects\\demo"
with_extension: projects\demo\notes.md
data\a.txt
C:\other\a.txt
Normal("a") Normal("b") ParentDir Normal("c.txt") 

What to learn from the output:

  1. The separator follows the system. The same source prints projects/demo/notes.txt when built for macOS.
  2. join and push with an absolute path discard the left side. If name comes from outside (a file, the network), joining it onto a base folder can escape the folder. Reject any such name that is absolute or contains .. before joining.
  3. a/b/../c.txt is parsed with ParentDir. Paths are not simplified for you; components() shows the structure. Windows accepts / as well as \ in paths you give it, so Path::new("a/b") works on both.
  4. Use the accessors. file_name, extension, parent and with_extension handle edge cases (a name with several dots, a trailing separator) that string splitting gets wrong.

Common mistakes#

  • Hard-coding \\ or / in a string path.
  • Converting to String with to_str().unwrap() for every operation. Keep values as Path/PathBuf until you show them to a person; see the thread on non-UTF-8 paths.
  • Comparing paths as strings. C:\A and c:\a are the same folder on Windows.

What does display() do?#

It gives a value that prints the path for humans. It is for output only; do not parse its text.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet