C and C++

C / C++ program to emulate the unix ln command

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
int main(int argc, char * argv[])
{
if(argc < 3 || argc > 4 || (argc == 4 && strcmp(argv[1],”-s”)))
{
printf(“Usage: ./a.out [-s] \n”);
return 1;
}
if(argc == 4)
{
if((symlink(argv[2], argv[3])) == -1)
printf(“Cannot create symbolic link\n”) ;
else
printf(“Symbolic link created\n”) ;
}
else
{
if((link(argv[1], argv[2])) == -1)
printf(“Cannot create hard link\n”) ;
else
printf(“Hard link created\n”) ;
}
return 0;
}
Sample Output:
Usage: ./a.out [-s]
[root@localhost uspl]# ./a.out 1 2 3 4
Usage: ./a.out [-s]
[root@localhost uspl]# ./a.out 1.c z
Hard link created
[root@localhost uspl]# ls -l
-rw-r--r-- 2 root root 657 Mar 27 16:44 1a.c
-rw-r--r-- 2 root root 657 Mar 27 16:44 z
[root@localhost uspl]# ./a.out 1a.c z
Cannot create hard link (Because z already exists)
[root@localhost uspl]# ./a.out -s 1a.c zz
Symbolic link created
[root@localhost uspl]# ls -l
-rw-r--r-- 2 root root 657 Mar 27 16:44 1a.c
lrwxrwxrwx 1 root root 4 Apr 1 18:32 zz ->
1a.c

Leave a comment

Your email address will not be published. Required fields are marked *