-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathhln.c
64 lines (62 loc) · 1.67 KB
/
hln.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libgen.h>
#include <sys/syslimits.h>
#include <sys/stat.h>
/*
* On Mac OSX, we can't create hard links on directories using the ln command..
*
* Install:
* make
* [sudo] make install
*/
char* get_real_destination(char* src, char* dst) {
//If dst is a directory /foo and src is /a/b/c
//the actual destination will become /foo/c
char* final_dst = malloc(PATH_MAX);
strcpy(final_dst, dst);
struct stat dst_stat;
if(stat(dst, &dst_stat) == 0)
{
if(S_ISDIR(dst_stat.st_mode))
{
char* src_file = basename(src);
final_dst[strlen(dst)] = '/';
strcpy(final_dst+strlen(dst)+1, src_file);
}
}
return final_dst;
}
int main(int argc, char* argv[]) {
//Make sure we have the right arguments
if (argc == 1 || argc > 3)
{
fprintf(stderr,"Usage:\t%s source [destination]\n", argv[0]);
fprintf(stderr,"\t hard links the source directory to the destination\n");
fprintf(stderr,"\t%s -u destination\n", argv[0]);
fprintf(stderr,"\t unlinks the destination directory\n");
return 1;
}
int ret = 0;
if(argc == 3 && strcmp(argv[1], "-u") == 0)
{
ret = unlink(argv[2]);
}
else if(argc == 2)
{
//No destination specified, use current directory
char cwd[PATH_MAX];
char* dst = get_real_destination(argv[1], getcwd(cwd, PATH_MAX));
ret = link(argv[1], dst);
}
else
{
char* dst = get_real_destination(argv[1], argv[2]);
ret = link(argv[1], dst);
}
if(ret != 0)
perror(argv[0]);
return ret;
}