I need to compare relative file paths between Windows and POSIX-flavor systems.
On Unix you could round-trip through bytes and replace
/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.
Don't have a machine handy to verify. ↩︎
Is it safe to directly replace
'/' 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
/ and change the meaning of the path, for example.
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.
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.
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:\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.