Shane Bishop
Shane Bishop

Reputation: 4750

How to get root of filesystem in Go in an OS-agnostic way

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:

I looked at this answer to a related question, but this also has some problems:

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

Answers (2)

Eurospoofer
Eurospoofer

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

dave
dave

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

Related Questions