在Go中获取系统文件夹路径?

时间:2013-08-05 02:50:23

标签: go cross-platform tempdir system-paths

是否有可能以跨平台的方式在Go中获取系统文件夹的路径?例如。临时文件夹,“文档”文件夹等

我找到了ioutil.TempFolder/File,但他们做了不同的事情。有什么想法吗?

5 个答案:

答案 0 :(得分:2)

内置选项尚不存在。您最好的选择是open an issue并提交功能请求。

与此同时,您可以使用platform specific +build flags自行添加支持。有了这个,你有几个选择:

  1. 使用os package获取每个系统的信息,可能通过shell获取。
  2. cgo与现有的C / C ++方法结合使用。请参阅this answer,其中介绍了如何使用C ++ for Windows获取此信息。
  3. 阅读os包的源代码以查看如何获取特定于平台的信息也可能会有所帮助。这可以帮助您设计获取此信息的方法,并可能提交要包含的补丁。

答案 1 :(得分:1)

除了Luke提到的方法,在Windows上你可以从environment variables获得一些路径。同样适用于Unix($ HOME等)。

答案 2 :(得分:1)

目前无法以跨平台方式访问标准系统文件夹。主目录虽然可以使用user package

进行访问
u, _ := user.Current()
fmt.Println(u.HomeDir)

答案 3 :(得分:0)

在2020年,我试图获得类似的结果,但仅适用于跨目录的临时目录。当我找到该线程并阅读一些答案时,我几乎得出结论,认为这是不可能的。

但是经过一些进一步的研究,我发现go已经有了它。就像接受的答案所指出的那样,它位于os包中。根据{{​​3}}这个文档,我们可以通过调用TempDir()函数来获取它。

我的建议是,如果有人试图查看另一个OS系统目录路径,并偶然发现了该线程,请尝试做一些进一步的研究。看起来当前go具有关于OS系统目录的更完整的功能。

答案 4 :(得分:0)

对于操作系统的临时目录,如Bayu所说,有一个内置函数os.TempDir() string来获取操作系统特定的临时目录:

// TempDir returns the default directory to use for temporary files.
//
// On Unix systems, it returns $TMPDIR if non-empty, else /tmp.
// On Windows, it uses GetTempPath, returning the first non-empty
// value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
// On Plan 9, it returns /tmp.
//
// The directory is neither guaranteed to exist nor have accessible
// permissions.
func TempDir() string {
    return tempDir()
}

如果您为 ioutil.TempDir(dir, pattern string) (string, error) 参数提供空字符串,则 dir 函数实际使用它。查看第 5 行和第 6 行:

// TempDir creates a new temporary directory in the directory dir.
// The directory name is generated by taking pattern and applying a
// random string to the end. If pattern includes a "*", the random string
// replaces the last "*". TempDir returns the name of the new directory.
// If dir is the empty string, TempDir uses the
// default directory for temporary files (see os.TempDir).
// Multiple programs calling TempDir simultaneously
// will not choose the same directory. It is the caller's responsibility
// to remove the directory when no longer needed.
func TempDir(dir, pattern string) (name string, err error) {