Summary Files Commits Branches @commit @diff @stats
path: root / chwrite / chwrite.c
blob: 6be8ec84b4d9afff06b237a88f2ab4bdfca28d80 (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
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.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;
    }

    operation = argv[1][0];

    if (operation != '+' && operation != '-') {
        help_message();
        return 1;
    }

    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;
}