aboutsummaryrefslogtreecommitdiffstats
path: root/usr/mv.c
blob: 76d9e62119a4ce9e5bb1431cca64c99d87464e5d (plain) (blame)
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
#include "gbos.h"
/* mv SRC DST: there is no rename syscall, so this is cp + rm. The copy has to
 * succeed before the source is removed - a half-copied DST plus a deleted SRC
 * loses the file. */

static unsigned char streq(const char *a, const char *b) {
    while (*a && *a == *b) {
        a++;
        b++;
    }
    return (unsigned char)(*a == *b);
}

void main(void) {
    char *argv[4];
    unsigned char argc = argv_parse(argv, 4);
    unsigned char in, out;
    int ch;

    if (argc < 2) {
        puts("usage: mv SRC DST");
        nl();
        sexit(2);
    }
    if (streq(argv[0], argv[1])) sexit(0); /* nothing to do */

    in = open(argv[0], O_READ);
    if (in == EISDIR) {
        puts("mv: SRC is a directory");
        nl();
        sexit(2);
    }
    if (in == NOFD) {
        puts("mv: no such file: ");
        puts(argv[0]);
        nl();
        sexit(2);
    }
    out = open(argv[1], O_WRITE);
    if (out > 3) {
        puts("mv: cannot create ");
        puts(argv[1]);
        nl();
        close(in);
        sexit(2);
    }
    while ((ch = fgetc(in)) >= 0) fputc(out, (char)ch);
    close(in);
    close(out);
    fremove(argv[0]); /* only now is it safe */
}