Can I force filepath.Abs to give path deisgned for another OS?

huangapple go评论100阅读模式
英文:

Can I force filepath.Abs to give path deisgned for another OS?

问题

我目前正在使用Windows。我使用以下代码来获取相对路径的绝对路径。

absolutePath, err := filepath.Abs(relativePath)

这个代码的输出是C:\project\test。有没有办法“欺骗”filepath.Abs函数,使其返回Linux风格的绝对路径,无论是/project/test还是/d/project/test/?谢谢!

英文:

I currently am working on Windows. I use the following code to get an absolute path for a relative path.

absolutePath, err := filepath.Abs(relativePath)

The output for this is C:\project\test. Is there any way to "trick" filepath.Abs to have a Linux style absolute path, whether it's /project/test or /d/project/test/? Thanks!

答案1

得分: 1

如@JimB所指出的,将相对路径转换为绝对路径不仅取决于操作系统,还取决于上下文:在不同系统上(无论操作系统如何),相同的相对路径可能会产生不同的路径;实际上,即使在同一系统上,从不同的工作目录转换相对路径到绝对路径也可能会产生不同的路径。正如@JimB所指出的,你可以使用path.Clean来删除任何不必要或冗余的相对路径组件(例如将/dir/../otherDir/./subDir/转换为/otherDir/subDir/),但这是你能得到的与上下文无关的最接近的结果。

如果你只想转换表示,可以使用filepath.ToSlash将所有特定于平台的分隔符替换为正斜杠。如果你想在不同系统之间重用路径,可以在输入上运行ToSlash,使用正斜杠存储“通用”路径,然后在目标系统上使用filepath.FromSlash将其转换回特定于平台的路径分隔符。

英文:

As @JimB noted, converting a relative path to an absolute path is not only OS-specific, it's context-specific: the same relative path on different systems (regardless of OS) can yield different paths; in fact, even on the same system, converting relative to absolute from different working directories can yield different paths. Again as @JimB noted, you can use path.Clean to remove any unnecessary or reduntant relative path components (e.g. turn /dir/../otherDir/./subDir/ into /otherDir/subDir/), but that's the closest you'll get to anything not context-sensitive.

If you just want to convert the representation, there's filepath.ToSlash which will replace all platform-specific separators with forward slashes. If you're trying to re-use a path across systems, you could run ToSlash on the input, store the "generic" path using forward slashes, then on the target system use filepath.FromSlash to convert it back to the platform-specific path separator.

huangapple
  • 本文由 发表于 2017年6月2日 22:13:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/44331078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定