UNIX writes a file's permissions as three octal digits, such as 754: one digit each for the user (owner), the group and others. In each digit, 4 means read, 2 write and 1 execute.
What to build
Turn octal permission modes into the nine-letter form that ls -l shows.
Requirements
- For each mode, print the mode, a space, and nine characters: for each of user, group and others,
ror-, thenwor-, thenxor-.
Input
The first line has q (1 ≤ q ≤ 20). Each of the next q lines has a mode of three octal digits (000 to 777).
Output
One line per mode, such as 754 rwxr-xr--.
Constraints
Every mode has exactly three digits, each from 0 to 7.
Example
Input:
3
754
644
700
Output:
754 rwxr-xr--
644 rw-r--r--
700 rwx------
Why it works
Each octal digit is exactly three bits, so one digit describes one class. The digit 7 is all three bits (rwx), 5 is r-x, 4 is r--, and 0 is nothing. Testing the bits with & is what the kernel does when it checks whether you may open a file.
Examples
3 754 644 700
754 rwxr-xr-- 644 rw-r--r-- 700 rwx------
2 777 000
777 rwxrwxrwx 000 ---------
Hints
Hint 1
Read each mode as a string of three octal digits, such as 754. The digit for each class is the character minus '0'.
Hint 2
In each digit, bit 4 is r, bit 2 is w and bit 1 is x. Test with (digit & 4), (digit & 2), (digit & 1).
Hint 3
Print the three classes one after another: user, group, others, nine characters in all.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int q;
char mode[8];
scanf("%d", &q);
for (int i = 0; i < q; i++) {
scanf("%7s", mode);
printf("%s ", mode);
for (int k = 0; k < 3; k++) {
int d = mode[k] - '0';
printf("%c%c%c", (d & 4) ? 'r' : '-', (d & 2) ? 'w' : '-', (d & 1) ? 'x' : '-');
}
printf("\n");
}
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step