71 lines
1.3 KiB
C
71 lines
1.3 KiB
C
|
|
#include <stdio.h>
|
||
|
|
#include <stdlib.h>
|
||
|
|
#include <string.h>
|
||
|
|
#include <sys/stat.h>
|
||
|
|
#include <sys/types.h>
|
||
|
|
|
||
|
|
static void usage (void);
|
||
|
|
|
||
|
|
mode_t
|
||
|
|
calculate_permission (char *arg_str)
|
||
|
|
{
|
||
|
|
const char perms[4] = "rwx";
|
||
|
|
|
||
|
|
if (strlen (arg_str) != 3)
|
||
|
|
{
|
||
|
|
usage ();
|
||
|
|
exit (EXIT_FAILURE);
|
||
|
|
}
|
||
|
|
|
||
|
|
mode_t permission = 0;
|
||
|
|
|
||
|
|
for (size_t j = 0; j < 3; j++)
|
||
|
|
{
|
||
|
|
int perm = 1 << (2 - j);
|
||
|
|
if (arg_str[j] == perms[j])
|
||
|
|
{
|
||
|
|
permission |= perm;
|
||
|
|
}
|
||
|
|
else if (arg_str[j] != '-')
|
||
|
|
{
|
||
|
|
usage ();
|
||
|
|
exit (EXIT_FAILURE);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return permission;
|
||
|
|
}
|
||
|
|
|
||
|
|
int
|
||
|
|
main (int argc, char **argv)
|
||
|
|
{
|
||
|
|
if (argc != 5)
|
||
|
|
{
|
||
|
|
usage ();
|
||
|
|
return EXIT_FAILURE;
|
||
|
|
}
|
||
|
|
|
||
|
|
mode_t user = calculate_permission (argv[1]);
|
||
|
|
mode_t group = calculate_permission (argv[2]);
|
||
|
|
mode_t other = calculate_permission (argv[3]);
|
||
|
|
|
||
|
|
mode_t permissions = (user << 6) | (group << 3) | other;
|
||
|
|
|
||
|
|
if (chmod (argv[4], permissions) == -1)
|
||
|
|
{
|
||
|
|
perror ("Failed to chmod");
|
||
|
|
return EXIT_FAILURE;
|
||
|
|
}
|
||
|
|
|
||
|
|
return EXIT_SUCCESS;
|
||
|
|
}
|
||
|
|
|
||
|
|
static void
|
||
|
|
usage (void)
|
||
|
|
{
|
||
|
|
printf ("chmod, changes permissions on a file\n");
|
||
|
|
printf ("usage: chmod USR GRP OTH FILE\n\n");
|
||
|
|
printf ("USR, GRP, and OTH must be of the rwx format,\n");
|
||
|
|
printf ("with - indicating a permission is not allwed.\n");
|
||
|
|
}
|