22

tl;dr:我如何询问 Windows 系统上当前的目录分隔符是什么?


不同版本的 Windows 似乎表现不同(例如\/两者都适用于英文版本,¥ 显然适用于日文版本,₩ 显然适用于韩文版本,等等......

有什么办法可以避免硬编码,而是在运行时询问 Windows?

笔记:

理想情况下,解决方案不应该依赖于像 . 这样的高级 DLL ShlWAPI.dll,因为低级库也依赖于此。所以它应该真的取决于kernel32.dllntdll.dll或类似......虽然我很难找到任何东西,无论是在高水平还是在低水平。

编辑:

一个小实验告诉我,它是 Win32 子系统(即kernel32.dll......或者它可能RtlDosPathNameToNtPathName_Untdll.dll?不确定,没有测试......)将正斜杠转换为反斜杠,而不是内核。(前缀\\?\使后面的路径中无法使用正斜杠——并且 NT 本机用户模式 ​​API 也因正斜杠而失败。)

所以显然它不是完全“内置”Windows,而只是一个兼容性功能——这意味着你不能盲目地用斜杠代替反斜杠,因为任何随机前缀\\?\到路径的程序都会在正斜杠上自动中断。

我对对此做出什么结论有复杂的感觉,但我只是想我会提到它。

(我将其标记为“路径分隔符”,即使这在技术上是不正确的,因为路径分隔符用于分隔路径,而不是目录(;vs. \)。希望人们明白我的意思。)

4

3 回答 3

35
于 2011-09-06T03:42:01.583 回答
4

The original poster added the phrase "kernel-mode" in a comment to someone else's answer.

If the original question intended to ask about kernel mode, then it probably isn't a good idea to depend on / being a path separator. Different file systems allow different character sets on disk. Different file system drivers in Windows can also allow different characters sets, which normally cannot include characters which the underlying file systems don't accept on disk, but sometimes they can behave strangely. For example Posix mode allows a component name to contain some characters in a path name in an NTFS partition, even though NTFS ordinarily doesn't allow those characters. (But obviously / isn't one of them, in Posix.)

In kernel mode in Unicode, U+005C is always a backslash and it is always the path separator. Unicode code points for yen and won are not U+005C and are not path separators.

In kernel mode in ANSI, complications arise depending on which ANSI code page. In code pages that are sufficiently similar to ASCII, 0x5C is a backslash and it is the path separator. In ANSI code pages 932 and 949, 0x5C is not a backslash but 0x5C might be a path separator depending on where it occurs. If 0x5C is the first byte of a multibyte character, then it's a yen sign or won sign and it is a path separator. If 0x5C is the second byte of a multibyte character, then it's not a character by itself, so it's not a yen sign or won sign and it's not a path separator. You have to start parsing from the beginning of the string to figure out if a particular char is actually a whole character or not. Also in Chinese and UTF-8, multibyte characters can be longer than two chars.

于 2011-09-06T05:20:55.100 回答
2

The standard forward slash (/) has always worked in all versions of DOS and Windows. If you use it, you don't have to worry about issues with how the backslash is displayed on Japanese and Korean versions of Windows, and you also don't have to special-case the path separator for Windows as opposed to POSIX (including Mac). Just use forward slash everywhere.

于 2011-09-06T04:25:41.087 回答