Kingusss12 Kingusss12 - 1 month ago 10
C Question

Convert string to mode_t

I have a character string "rwxrwxrwx".

How can I convert it to type mode_t to use in a chmod system call? The permissions should be -rwxrwxrwx.

Thank you for all your help!

Answer

You could use this code. However, it can be shortened with a for loop and some modulos.

const char *perm = "rwxrwxrwx";
mode_t mode = 0;

if (perm[0] == 'r')
  mode |= 0400;
if (perm[1] == 'w')
  mode |= 0200;
if (perm[2] == 'x')
  mode |= 0100;
if (perm[3] == 'r')
  mode |= 0040;
if (perm[4] == 'w')
  mode |= 0020;
if (perm[5] == 'x')
  mode |= 0010;
if (perm[6] == 'r')
  mode |= 0004;
if (perm[7] == 'w')
  mode |= 0002;
if (perm[8] == 'x')
  mode |= 0001;
Comments