Simvik

Show permissions like ls

Format a file's mode bits as ls -l does, including setuid, setgid and sticky. A medium embedded C problem (Linux userspace basics), run and graded in the…

medium · Linux userspace basics · linux · permissions · bits

ls -l shows a file's type and permissions as 10 characters, such as -rwxr-xr-x or drwxrwxrwt:

  • character 1: the type: d directory, l symbolic link, c character device, - regular file (from the type argument),
  • then three groups of rwx for owner, group and others (octal 0400 down to 0001), - where a bit is clear,
  • special bits replace the execute character: setuid (04000) in the owner group and setgid (02000) in the group group show s, or S if that execute bit is clear; the sticky bit (01000) in the others group shows t, or T.

Write mode_string(type, mode, out).

Starter code

void mode_string(char type, unsigned mode, char *out) {
  const char *rwx = "rwxrwxrwx";
  out[0] = type;
  for (int i = 0; i < 9; i++) out[1 + i] = (mode & (0400 >> i)) ? rwx[i] : '-';
  out[10] = 0;
}

Example tests

Ordinary files

show('-', 0644);
show('-', 0755);
show('d', 0750);

Expected output:

- 00644: -rw-r--r--
- 00755: -rwxr-xr-x
d 00750: drwxr-x---

Device nodes and links

show('c', 0660);
show('l', 0777);

Expected output:

c 00660: crw-rw----
l 00777: lrwxrwxrwx

Learn it first