[Function] FilesHardLinked() - Detect if two files are hardlinks (links pointing to the same file)

Post your working scripts, libraries and tools for AHK v1.1 and older
seven
Posts: 8
Joined: 22 Mar 2016, 02:16

[Function] FilesHardLinked() - Detect if two files are hardlinks (links pointing to the same file)

24 Oct 2019, 04:09

This function is a simple method of detecting if two files are hard links, e.g. two links pointing to the same file.
FilesHardLinked.ahk
(1.92 KiB) Downloaded 89 times

Code: Select all

/*
	Function:      FilesHardLinked()	               
	Author:        seven	               
	Date:          2019/10/24	               
	Description:   Checks if two files are "hard links to one another"
	               
	Input:         file1, file2 - paths to each file	               
	Output:        1 - yes, the files are hard links e.g. links pointing to the same file
				   0 - they are not hard links (they are two different files)
	               
	Remarks:       Attributes of File1 are changed temporarily—if the attributes of File2 also change,
				   the files are hardlinks of one another. 
				   Idea from: https superuser.com /questions/366739/how-can-i-find-hard-links-on-windows  Broken Link for safety
*/
/* Proof Code:
file1 := A_Desktop "\test-file-1"
file2 := A_Desktop "\test-file-2"
file3 := A_Desktop "\test-file-3"
FileAppend,test file 1 and 2 , %file1%
FileAppend,test file 3       , %file3%
DllCall("CreateHardLink",Str,file2,Str,file1,Int,0)
msgbox % "Files 1 & 2:  " (FilesHardLinked(file1,file2)?"yes":"no") 
     . "`nFiles 1 & 3:  " (FilesHardLinked(file1,file3)?"yes":"no")
FileDelete % A_Desktop "\test-file-1"
FileDelete % A_Desktop "\test-file-2"
FileDelete % A_Desktop "\test-file-3"
exitapp
*/
; ---------------------------------
FilesHardLinked(file1,file2)
; ---------------------------------
{
	FileGetAttrib,a1,%file1%     ; get attribs for both files
	FileGetAttrib,a2,%file2%	
	If (a1<>a2)                  ; if the attribs are not the same, 
		return 0                 ; the links are not to the same file	
	FileSetAttrib,^A,%file1%,0,0 ; toggle the 'Archive' attrib of file1
	FileGetAttrib,a1,%file1%     ; get new attribs for both files
	FileGetAttrib,a2,%file2%	
	FileSetAttrib,^A,%file1%,0,0 ; restore original 'Archive' attribute of file1
	                             ; if the attribs changed for both links,
	return a1=a2 ? 1 : 0         ; the links are to the same file and are hard links
}
(For search: hard link, hard links, hardlink, hardlinks, hard linked, hardlinked, symbolic link, symbolic links, soft link, soft links, softlink, softlinks, shadow, shadows, alias, aliases)

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: Bing [Bot] and 141 guests