Last active
May 21, 2023 19:58
-
-
Save betelgeuse-7/23934b0f250389d4a290014feac3d106 to your computer and use it in GitHub Desktop.
Creating a hardlink using cgo.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"syscall" | |
) | |
/* | |
#include <fcntl.h> | |
#include <unistd.h> | |
int _linkat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags) { | |
return linkat(olddirfd, oldpath, newdirfd, newpath, flags); | |
} | |
*/ | |
import "C" | |
func main() { | |
osArgs, osArgsLen := os.Args, len(os.Args) | |
if osArgsLen != 3 { | |
fmt.Println("hardlink: 3 arguments needed") | |
os.Exit(1) | |
} | |
origFile, hlinkFile := osArgs[1], osArgs[2] | |
_, err := os.Open(origFile) | |
if err != nil { | |
if os.IsNotExist(err) { | |
fmt.Printf("File %s does not exist\n", origFile) | |
os.Exit(1) | |
} | |
fmt.Printf("Unknown error: %s\n", err.Error()) | |
os.Exit(1) | |
} | |
makeHardlink(origFile, hlinkFile) | |
} | |
func makeHardlink(origFilePath, newFilePath string) { | |
origFilePathC := C.CString(origFilePath) | |
newFilePathC := C.CString(newFilePath) | |
result := C._linkat(C.AT_FDCWD, origFilePathC, C.AT_FDCWD, newFilePathC, 0) | |
fmt.Println(result) | |
if result < 0 { | |
fmt.Print("errno: ") | |
fmt.Println(syscall.Errno(-result)) | |
fmt.Println("Error creating hardlink") | |
os.Exit(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment