How to normalize Windows's "\" to "/" when display or convert `Path` to string?

I need to compare relative file paths between Windows and POSIX-flavor systems.

I believe if you're on Windows, both style is recognized and you can just compare them with == or otherwise inspect their components.[1]

On Unix you could round-trip through bytes and replace \\s with /s. Or convert to String and do the conversion there, under the premise that non-UTF8 paths aren't worth trying to compare across the platforms.


  1. Don't have a machine handy to verify. ↩ī¸Ž

1 Like

Is it safe to directly replace '\\' with '/' after converting to UTF-8?

I don't know what you mean by safe. And a good guess requires more context.

In the general case, a unix path can have \\ in it which aren't component separators, so it's possible to blindly convert all \\ to / and change the meaning of the path, for example.

1 Like

Disclaimation: I came across this crate, but never give it (or any path crate) a try. Maybe there are some other great path libraries I don't bother looking for.

2 Likes

The question isn't clear: It is safe for what ?

The java language has solved this to make stuff "portable". It introduces the concept of a "canonical path".

A moot point is that you can't compare full paths, only relative ones: Linux doesn't have "drive C:" and "drive E:", and the translation between mounts is dependent on where the drivers are mounted: ubuntu WSL mounts at /mnt/e and /mnt/e . git bash, to /c/ and /e/...

In general, yes, you can consider it safe to replace \ with / to make platform neutral(ish) paths.

Another thing you may need to watch for is that windows is typically case insensitive, while unixes in general are case sensitive.

Mind that you must be very careful with symbolic links on linux: that is why java has the concept of canonical paths: to solve links and '.' and '..' references.

1 Like

Windows doesn't accept / as path separator for verbatim paths (paths that start with \\?\). Instead it is interpreted as part of the file/directory name. That is C:\foo/bar.txt is file bar.txt inside a directory foo inside the drive C:, while \\?\C:\foo/bar.txt is a file called foo/bar.txt inside the drive C:. Verbatim paths are necessary if you want to avoid the windows limitation that paths are at most 254 characters long (declaring long path compatibility in the application manifest and setting a register to enable long path also works) and std::fs::canonicalize (which resolves symlinks and such) returns verbatim paths.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.