Permission Flags
Completed
Use #define READ 4, WRITE 2, EXEC 1. Read a permission number 0–7 and a list of operations (+r, -w, …) that add or remove flags. Print the final number and the rwx string (with - for missing).
Input
Line 1: starting value. Line 2: k. Then k operations.
Output
One line: N rwx
Example
Input
4 2 +w +x
Output
7 rwx
Editor
C
Hints
Set a flag with |, clear it with & ~flag, test it with &.
Solution explanation
This is exactly how Unix file permissions (like 755) work.
Show solution
#include <stdio.h>
#define READ 4
#define WRITE 2
#define EXEC 1
int main() {
int perm, k;
char op[3];
scanf("%d %d", &perm, &k);
for (int i = 0; i < k; i++) {
scanf("%s", op);
int flag = EXEC;
if (op[1] == 'r') flag = READ;
else if (op[1] == 'w') flag = WRITE;
if (op[0] == '+') perm = perm | flag;
else perm = perm & ~flag;
}
printf("%d %c%c%c\n", perm, perm & READ ? 'r' : '-', perm & WRITE ? 'w' : '-', perm & EXEC ? 'x' : '-');
return 0;
}