How to find the mountpoint a file resides on?

后端 未结 8 1726
半阙折子戏
半阙折子戏 2020-12-03 17:16

For example, I\'ve got a file with the following path:

/media/my_mountpoint/path/to/file.txt

I\'ve got the whole path and want to get:

8条回答
  •  暖寄归人
    2020-12-03 17:53

    @larsmans Very good answer, this was very helpfull! I have implemented this in Golang where I needed it.

    For people who are interested in the code (this has been tested for OS X and Linux):

    package main
    
    import (
        "os"
        "fmt"
        "syscall"
        "path/filepath"
    )
    
    func Mountpoint(path string) string {
        pi, err := os.Stat(path)
        if err != nil {
            return ""
        }
    
        odev := pi.Sys().(*syscall.Stat_t).Dev
    
        for path != "/" {
            _path := filepath.Dir(path)
    
            in, err := os.Stat(_path)
            if err != nil {
                return ""
            }
    
            if odev != in.Sys().(*syscall.Stat_t).Dev {
                break
            }
    
            path = _path
        }
    
        return path
    }
    
    func main() {
        path, _ := filepath.Abs("./")
        dir := filepath.Dir(path)
        fmt.Println("Path", path)
        fmt.Println("Dir", dir)
        fmt.Println("Mountpoint", Mountpoint(path))
    }
    

提交回复
热议问题