Create Hardlink with golang
Asked Answered
D

1

9

I want to create a hardlink to a file using golang. os.Link() tells me, that windows is not supported. Therefore i tried to use os.exec, to call "mklink.exe".

cmd := exec.Command("mklink.exe", "/H", hardlink_path, file_path)
err := cmd.Run()

However, it tells me, that it can't find mklink.exe in %PATH%. This baffels me, since i can call it using cmd.

Next i tried to call it indirectly via cmd:

cmd := exec.Command("cmd.exe", "mklink.exe", "/H", hardlink_path, file_path)
err := cmd.Run()

Now it does not return any error, however, it also doesn't create a hardlink. Any suggestions?

Dempsey answered 28/5, 2013 at 19:36 Comment(1)
Can you change the accepted answer?Sharpeyed
C
16

Golang support for native Windows hard links was added in Go 1.4. Specifically, this commit makes the following snippet work:

err := os.Link("original.txt", "link.txt")

Beware that not all Windows file systems support hard links. Currently NTFS and UDF support it, but FAT32, exFAT and the newer ReFS do not.

Full example code:

package main

import (
    "log"
    "os"
    "io/ioutil"
)

func main() {   
    err := ioutil.WriteFile("original.txt", []byte("hello world"), 0600)
    if err != nil {
        log.Fatalln(err)
    }    

    err = os.Link("original.txt", "link.txt")
    if err != nil {
        log.Fatalln(err)
    }
}
Callicrates answered 27/11, 2015 at 17:31 Comment(2)
Is there a buitlin way of checking if the current file system supports hard links? Or does the os.Link returns an error on such file systems?Sharpeyed
Currently (in May 2021) there does not appear to be a built-in way to check if a filesystem supports hard links. os.Link does return an error if CreateHardLink() fails. If you really wanted to, on Windows, you could call GetVolumeInformation (see this answer) and check FileSystemFlags for FILE_SUPPORTS_HARD_LINKS.Callicrates

© 2022 - 2024 — McMap. All rights reserved.