Summary Files Commits Branches @commit @diff @stats
path: root / chwrite / chwrite.c
blob: 395cf913c0fa91de2efc5c7209ea84a0c42f8261 (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>

static void
help_message(void) {
    printf(
        "chwrite [-h|--help]\n"
        "chwrite +|+w|-|-w FILE...\n"
        "\n"
        "Change write permissions for file(s)\n"
    );
}

int
main(int argc, char *argv[]) {
    int i = 0, f = 0, result = 0;
    struct stat fs = { 0, };
    char operation;

    if (argc <= 1) {
        help_message();
        return 0;
    }
    for (i = 1; i < argc; ++i) {
        if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
            help_message();
            return 0;
        }
    }

    if (!strcmp(argv[1], "+") || !strcmp(argv[1], "+w")) {
        operation = '+';
    }
    else if (!strcmp(argv[1], "-") || !strcmp(argv[1], "-w")) {
        operation = '-';
    }
    else {
        printf("Invalid argument '%s'!\n", argv[1]);
        help_message();
        return 1;
    }

    if (argc == 2) {
        printf("Not enough arguments!\n");
        help_message();
        return 2;
    }

    for (i = 2; i < argc; ++i) {
        f = open(argv[i], 0);
        if (f == -1)
            return errno;

        result = fstat(f, &fs);
        if (result == -1)
            return errno;

        if (operation == '+')
            fs.st_mode |=   S_IWUSR;
        else
            fs.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);

        result = fchmod(f, fs.st_mode);
        if (result == -1)
            return errno;
    }
    return result;
}