summaryrefslogtreecommitdiffstats
path: root/usr/utils/mv.c
blob: e3f38ed9ea55174d97dd407ed73a9a950ab4cc50 (plain)
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
65
66
67
68
69
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <linux/limits.h>

int main(int argc, char *argv[])
{
	int c, f;
	char *p;
	struct stat sb;

	f = 0;
	do {
		c = getopt(argc, argv, "f");
		if (c == EOF)
			break;

		switch (c) {

		case 'f':
			f = 1;
			break;
		case '?':
			fprintf(stderr, "%s: invalid option -%c\n",
				argv[0], optopt);
			return 1;
		}

	} while (1);

	if (optind == argc) {
		fprintf(stderr, "Usage: %s [-f] source dest\n", argv[0]);
		return 1;
	}

	memset(&sb, 0, sizeof(struct stat));
	if (stat(argv[argc - 1], &sb) < 0 && argc - optind > 2) {
		if (!(S_ISDIR(sb.st_mode))) {
			fprintf(stderr,
				"multiple targets and %s is not a directory\n",
				argv[argc - 1]);
			return 1;
		}
	}

	for (c = optind; c < argc - 1; c++) {
		char target[PATH_MAX];

		p = strrchr(argv[c], '/');
		p++;

		if (S_ISDIR(sb.st_mode))
			snprintf(target, PATH_MAX, "%s/%s", argv[argc - 1], p);
		else
			snprintf(target, PATH_MAX, "%s", argv[argc - 1]);

		if (f)
			unlink(target);

		if (rename(argv[c], target) == -1)
			perror(target);
	}

	return 0;
}