Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I watch for file changes on OS X?

I would like to be notified of writes into a given file – without polling, without having to read from the file and without having to monitor the parent directory and watch the file modification time stamps. How do I do that?

like image 807
zoul Avatar asked Jul 12 '12 08:07

zoul


People also ask

How do I find recently edited files on Mac?

(1) In the Finder, under File menu select Find and then you can specify all files modified after and/or before dates that you specify. Search over your entire computer or inside specific folders, but be aware that some folders are not searched by File/Find or by Spotlight.

Is the File Manager included in macOS?

Finder is a built-in file manager on macOS. Sometimes, you may find it inconvenient to use, especially when you're trying to copy or move a file to another folder. That's why more and more people are looking for alternatives to Finder.

Why are there X's on my files Mac?

Meaning of the red X icons DRACOON for Windows/Mac will mark files and folders that cannot (currently) be synchronized with a red X icon to draw attention to a synchronization problem.


1 Answers

I couldn’t find a simple example, so I’m contributing what I came up with for future reference:

@interface FileWatch ()
@property(assign) dispatch_source_t source;
@end

@implementation FileWatch
@synthesize source;

- (id) initWithPath: (NSString*) path targetQueue: (dispatch_queue_t) queue block: (dispatch_block_t) handler
{
    self = [super init];

    int descriptor = open([path fileSystemRepresentation], O_EVTONLY);
    if (descriptor < 0) {
        return nil;
    }

    [self setSource:dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor, DISPATCH_VNODE_WRITE, queue)];
    dispatch_source_set_event_handler(source, handler);
    dispatch_source_set_cancel_handler(source, ^{
        close(descriptor);
    });

    dispatch_resume(source);
    return self;
}

- (void) dealloc
{
    if (source) {
        dispatch_source_cancel(source);
        dispatch_release(source);
        source = NULL;
    }
}

@end
like image 149
zoul Avatar answered Nov 15 '22 10:11

zoul