I want to get the root directory of the filesystem in Go in such a way that it will work on both Windows and Unix.
I thought I could do something like
func fsRootDir() string {
s := os.Getenv("SystemDrive")
if s != "" {
return s
}
return "/"
}
However, there are a couple problems with this, so I rejected this approach:
SystemDrive
environment variable on Unix with some bogus path.SystemDrive
environment variable on Windows to some bogus path.I looked at this answer to a related question , but this also has some problems:
SystemDrive
environment variable, which for the reasons above is not guaranteed to hold the expected value on either Unix or Windows.os.TempDir
. On Windows, os.TempDir
uses GetTempPath
, returning the first non-empty value from %TMP%
, %TEMP%
, %USERPROFILE%
, or the Windows directory. I do not believe I can trust that these environment variables have not been modified.I also considered
func fsRootDir() string {
if runtime.GOOS == "windows" {
return "C:"
}
return "/"
}
but I thought I read somewhere that it is possible to change the filesystem root on Windows to something other than C:
.
How can I get the root directory of a filesystem in such a way that it will work on both Windows and Unix?
Why not combine the two?
func fsRootDir() string {
if runtime.GOOS == "windows" {
return os.Getenv("SystemDrive")
}
return "/"
}
A user could change the value of the SystemDrive environment variable on Windows to some bogus path.
No they can't, SystemDrive
is a read-only variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.