Create Hardlink with golang

I want to create a hard link to a file using golang. os.Link () tells me that windows are not supported. So I tried to use os.exec to call "mklink.exe".

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

However, this tells me that it cannot find mklink.exe in% PATH%. This makes me think, as I can call it with cmd.

Then I tried calling 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 errors, however it also does not create a hard link. Any suggestions?

+4
source share
2 answers

For instance,

 package main import ( "fmt" "os" "os/exec" ) func main() { hardlink_path := `link.hard` file_path := `link.go` _, err := os.Stat(file_path) if err != nil { fmt.Println(err) return } os.Remove(hardlink_path) cmd := exec.Command("cmd", "/c", "mklink", "/H", hardlink_path, file_path) out, err := cmd.CombinedOutput() if err != nil { fmt.Println(err) return } fmt.Print(string(out)) } 

Output:

 Hardlink created for link.hard <<===>> link.go 
+2
source

Gool support for native Windows hard links was added in Go 1.4. In particular, this commit does the following snippet:

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

Remember that not all Windows file systems support hard links. NTFS and UDF currently support it , but FAT32, exFAT, and new 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) } } 
+4
source

Source: https://habr.com/ru/post/1483217/


All Articles