Overview
- A file name gives an identity to some contents present in the disk. Through file names the disk contents are organised in meaningful and logical chunks. A hard link is another reference to the disk contents(i.e.,an already existing file) similar to a file name.
- Hard links have limitations that include:
- They can not point to a directory
- They can not point to files in another file system
- When a hard link is created the operating system increases its link count to the file(i.e, contents).
- When any of the links is deleted the link count is decreased. The file remains in the file system till all the hard links are deleted.
- A soft link is a special file that points to an existing file. Soft links are popularly known as symbolic links. When the original file is deleted the soft link still points to the non-existing file.
- A soft link can point to a directory. It can also point to a file or directory in another file system.
The function os.link() creates a hard link to an existing file.
Parameters
src – The path of the file for which the hard link is to be created(i.e, source path)
dst – The path of the hard link(i.e., destination path)
src_dir_fd – If provided, the source path is considered relative to the directory specified by this descriptor
dst_dir_fd – If provided, the destination path is considered relative to the directory specified by this descriptor
follow_symlinks – When the source path points to a symbolic link, the flag follow_symlinks directs whether to resolve the actual file pointed to or to stop with the symbolic link
Example
# Example Python program that creates a hard link
# to a file using the function os.link
import os
filePath = "./Rain.txt"
linkName = "RainLink"
# Create a hard link
os.link(filePath, linkName)
# Print the directory contents
print(os.listdir("."))Output
['songs', 'test', 'RainLink', 'contents.txt', 'AntAndGrasshopper.txt', 'BaaBaa.txt', 'RowYourBoat.txt', 'Copy of BaaBaa.txt', 'Rain.txt', 'Wheels.txt', 'test.txt', 'OneTwoBuckle.txt']Outout of ls -l
-rwxr--r-- 1 root1 wheel 148 May 5 23:21 AntAndGrasshopper.txt
-rw-r--r--@ 1 root1 wheel 170 May 4 21:06 BaaBaa.txt
-rwxr--r-- 1 root1 wheel 0 May 4 21:13 Copy of BaaBaa.txt
-rwxr--r-- 1 root1 wheel 132 May 5 23:25 OneTwoBuckle.txt
-rw-r--r--@ 2 root1 wheel 45 May 3 22:45 Rain.txt
-rw-r--r--@ 2 root1 wheel 45 May 3 22:45 RainLink
-rw-r--r--@ 1 root1 wheel 100 May 2 23:32 RowYourBoat.txt
-rw-r--r--@ 1 root1 wheel 40 May 2 20:50 Wheels.txt
-rw-r--r--@ 1 root1 wheel 38 Apr 3 19:59 contents.txt
drwxr-xr-x 9 root wheel 288 May 6 13:42 songs