D:跨平台移动到顶级路径的方式?

D: crossplatform way to move to top level of path?

我在变量中有如下路径:

D:\foo\bar\baz\file.txt

也可以是这样的:

/foo/bar/baz/file.txt

我需要跨平台的方法可能会移动到 bar 目录。

我只找到一种方法,但它看起来像 hack:

writeln(mystr.replaceLast("baz" ~ dirSeparator ~ "file.txt", ""));

出于某种原因,使用 dmd 2.068.2 的 dpaste 对此不太满意。但这是正确的代码。

import std.path;
import std.stdio;

void main() {
    version(Posix) {
        writeln(buildNormalizedPath("/a/b/c", "../d"));
    } else version(Windows) {
        writeln(buildNormalizedPath("c:\\a\b\c", "..\d"));
    }
}

std.path has 2 functions for this: buildNormalizedPath and asNormalizedPath.

它们之间的唯一区别是 asNormalizedPath 不会分配内存。