in Apps, Cocoa, Mac OS X, Objective-C

Calculating UNIX file permissions

Permissions Mac AppA few years ago I wrote a simple but handy Mac app that calculates unix file permissions using a matrix of check boxes. I wrote it because I wanted to better understand how those octal values get calculated and to expand my experience of writing Mac apps.

I was also learning some crazy assembly code at the time too so I was also making sense of putting bitwise operations to task. Rather than let this code languish on my hard drive, I thought I’d share…

The main nib file contains a matrix with the the button cells set to a check box style. The whole matrix has an action attached that calls the AppController’s calculatePermission: method. This method is quite simple and I’ve carefully commented it for you so please feel free to check it out. It loops around the matrix and bitwise OR up the checkbox values and then converts this into a C string. I decided to use a C string because the text version of the permissions can only be ASCII values and we might as well be as efficient as possible.

int i,octal = 0;
char *permission[8] = {"___", "__x", "_w_", "_wx", "r__", "r_x", "rw_", "rwx"};
char text[11] = "-";

// Loop through each row (user) - User, Group, All
for(i=0; i<3; i++) {

  // Loop through each column (permission bit) and OR up the results - r=4, w=2, x=1
  int c, row = 0;
  for(c = 0; c < 3; c++) {        
       We get our checkbox toggle bit and left shift to move it along a column.
       Next we do a bitwise OR which allows us to mask it. The result is 1 if the first bit
       is 1 OR the second bit is 1 OR both bits are set to 1. Else, the result is 0
       e.g. 0 << 0 = 00000000 = 0
            1 << 1 = 00000010 = 2
            1 << 2 = 00000100 = 4
    bool isTicked = [[sender cellAtRow:i column: c] state];
    row |= (isTicked << c); 
  // Concat this string row to the last. We want a big permissions char array :)
  strcat(text, permission[row]);
  row *= (int) pow(10, 2-i); // Shift row along into decimal 10's
  octal += row;

I’ve uploaded Permissions to GitHub in the hope that someone might find it useful when they’re learning Cocoa. If you do find it helpful please post a quick comment. Feedback is always appreciated.

Write a Comment


  1. There seems to be no license listing on the github version. Can you add a license of some sort so it is clear?