Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Check if a file can be deleted on a Mac
* checkFilePermissions.m
* Description: Check if a file can be deleted on a Mac
* Author: Chad Armstrong
* Date: 1 December 2017
* To compile: gcc -framework Foundation -framework AppKit checkFilePermissions.m -o checkFilePermissions
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
int main(int argc, char *argv[])
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSFileManager *fm = [NSFileManager defaultManager];
// I need a mix between the access and isDeletableFileAtPath methods to check
// if I need admin rights to erase the file. Also need to check if the volume
// is read-only (such as a CD-ROM or certain disk images).
if (argc <= 1) {
printf("No path specified.\n");
return -1;
char *path = argv[1];
NSString *objcPath = [NSString stringWithCString: path encoding: NSUTF8StringEncoding];
// Use UNIX access() call -----
if (access(path, W_OK) == 0) {
// have access rights to read
printf("You are A-OK to write to %s, boss.\n", path);
} else {
printf("Nope, you can't access %s, you sorry sack of pig droppings!\n", path);
// Use the NSFileManager methods -----
if ([fm isWritableFileAtPath: objcPath] == YES) {
NSLog(@"You can write to the file %@", objcPath);
} else {
NSLog(@"You CANNOT write to the file %@", objcPath);
if ([fm isDeletableFileAtPath: objcPath] == YES) {
NSLog(@"You can delete the file %@", objcPath);
} else {
NSLog(@"You CANNOT delete the file %@", objcPath);
// Get the attributes of the path and its file system
NSError *error = nil;
NSDictionary *fileAttr = [fm attributesOfItemAtPath: objcPath error: &error];
NSDictionary *fsAttr = [fm attributesOfFileSystemForPath: objcPath error: &error];
NSLog(@"fileAttr: %@", fileAttr);
NSLog(@"fsAttr: %@", fsAttr);
// Use NSWorkspace method -----
NSWorkspace * ws = [NSWorkspace sharedWorkspace];
BOOL removable = NO;
BOOL writeable = NO;
BOOL unmountable = NO;
NSString *fsDescription = nil;
NSString *fsType = nil;
// Check if the file system for the given path is read-only or not
[ws getFileSystemInfoForPath: objcPath
isRemovable: &removable
isWritable: &writeable
isUnmountable: &unmountable
description: &fsDescription
type: &fsType];
NSLog(@"removable: %@", removable ? @"YES" : @"NO");
NSLog(@"writeable: %@", writeable ? @"YES" : @"NO");
NSLog(@"unmountable: %@", unmountable ? @"YES" : @"NO");
NSLog(@"FS Description: %@", fsDescription);
NSLog(@"FS Type: %@", fsType);
[pool drain];
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment