Aim :

Write a C / C++ program to emulate the unix ln command.

Theory :

Links are created by giving alternate names to the original file. The use of links allows a large file, such as a database or mailing list, to be shared by several users without making copies of that file. Not only do links save disk space, but changes made to one file are automatically reflected in all the linked files. The ln command links the file designated in the SourceFile parameter to the file designated by the TargetFile parameter or to the same file name in another directory specified by the TargetDirectory parameter. By default, the ln command creates hard links.

To create a link to a file named chap1, type the following:

ln -f chap1 intro

This links chap1 to the new name, intro. When the -f flag is used, the file name intro is created if it does not already exist. If intro does exist, the file is replaced by a link to chap1. Both the chap1 and intro file names refer to the same file.

To link a file named index to the same name in another directory named manual, type the following:

ln index manual

This links index to the new name, manual/index. To link several files to names in another directory, type the following:

ln chap2 jim/chap3 /home/manual 

This links chap2 to the new name /home/manual/chap2 and jim/chap3 to /home/manual/chap3.

Code :


 #include<stdio.h>
 #include<unistd.h>
 int main(int argc, char *argv[])
 {
  if(argc!=3)
   {
     printf("Usage: %s <src_file><dest_file>\n",argv[0]);
     return 0;
   }
  if(link(argv[1],argv[2])==-1)
  {
   printf("Link Error\n");
   return 1;
  }
  printf("Files Linked\n");
  printf("Inode number of linked files\n");
  //display the inode linked files
  char str[100];
  sprintf(str,"ls -i %s %s\n",argv[1],argv[2]);
  system(str);
  return 0;
 }

Output :

  • Open a terminal.
  • Change directory to the file location in both the terminals.
  • Open a file using command followed by program_name
    vi 5b_unix_ln-command.c 
    and then enter the source code and save it.
  • Then compile the program using
    g++ 5b_unix_ln-command.c
  • Then create a dummy file with any of the name like abc.c .
  • If there are no errors after compilation execute the program using
    ./a.out abc.c out.c
    where abc.c is the source file and out.c is the new destination file to be given.
  • The inode numbers of both files are displayed on the screen verifying that the files are hard linked.

Screenshot :

Not Available