Reputation: 4750
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?
Upvotes: 0
Views: 766
Reputation: 682
Old post but a more updated solution might be the io.fs
// The forward slash works for both lin/unix and windows.
rootFS := os.DirFS("/")
if err := fs.WalkDir(rootFS, ".", func(path string, d fs.DirEntry, err error) error {
// process each item in the root here
fmt.Println(path)
// to ignore subdirectories (excluding root itself)
if d.IsDir() && path != "." {
return filepath.SkipDir
}
return nil
}); err != nil { log.Fatal(err) }
Upvotes: 1
Reputation: 64657
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.
Upvotes: 2