Question

I want to know when a new file is created on a specific directory, instead of scanning the directory from time to time.

I understand that there is a way to make the operating system tell my program that a new file was created. How does it work?

As noted, this has similarities with How to be notified of file/directory change in C/C++, ideally using POSIX

Was it helpful?

Solution

Depends on which OS.

On Windows, the base API would be Directory Change Notifications.

Since you mention Linux in the tags, this would be the inotify API.

To add to the OS X answer, as of 10.5, you want the FSEvents API.

OTHER TIPS

Under Linux, check out Inotify.

How to be notified of file/directory change in C/C++, ideally using POSIX

or search for inotify in stackoverflow you will get lots of ideas

FAM provides a consistent file-watching interface across all UNIXes. On Linux, the back-end daemon may be replaced by Gamin, but a program linked with FAM will work with Gamin just fine. (Behind the scenes, FAM may be using polling, and Gamin may be using inotify or dnotify or kqueue, but you shouldn't need to worry about the implementation.)

OS X.5 has FSEvents, which is very different in that it monitors the whole system instead of specified files and directories, but would also satisfy your needs.

On Windows, see Find(First|Next|Close)ChangeNotification or ReadDirectoryChanges.

FileSystemWatcher is the answer - and it works recursively.

There's an example here (search for FileSystemWatcher)

With Mac OS X, this functionality is part of the Spotlight API.

Using .Net on Windows (not sure about Linux/mono) you can use a FileSsytemWatcher to watch for new files and raise events when they are created.

From MSDN:

Use FileSystemWatcher to watch for changes in a specified directory. You can watch for changes in files and subdirectories of the specified directory. You can create a component to watch files on a local computer, a network drive, or a remote computer.

MSDN Page

The Windows API provides facilities for monitoring the file system - there's an example here http://msdn.microsoft.com/en-us/library/aa365261%28VS.85%29.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top