3

I'm making a program in C for linux that scans a directory every x seconds during a time period for modifications, but I'm having trouble finding out when a file or directory is created. Here are a few options I considered:

  • Using the stat struct, check if the last status change and data modification timestamps are the same. This brings up the problem that you can create a file, modify it before the program has a chance to check it, which changes the data modification timestamp and no longer sees it as a new file.

  • Keep a log of the name of every file/directory in the directory and check for new ones. This has the problem where you delete a file and then create a new one with the same name, it doesn't get interpreted as a new file.

  • Keep a count of the number of file/directories. Similliar problem to the last idea.

With that said, does anyone have any idea on how I can uniquely identify the creation of a file/directory?

user470379
  • 4,879
  • 16
  • 21
Mr eskimo
  • 41
  • 1

3 Answers3

4

You cannot, at least not this way. POSIX has no provisions for storing the file creation time in the file system, like Windows and some other OSes do. It only keeps the status change, access and modification times. Most Unix filesystems do not store that information either.

One of the reasons for this is the existence of hard links, since file timestamps are stored in their inodes and not in the directory references. What would you consider the creation time to be for a file that was created at 10am and then hard-linked into another directory at 11am? What if a file is copied?

Your best, but unfortunately OS-specific, approach would be to use whatever framework is available in your platform to monitor filesystem events, e.g. inotify on Linux and kqueue on FreeBSD and MacOS X...

EDIT:

By the way, Ext4fs on Linux does store inode creation times (crtime). Unfortunately getting to that information from userspace is still at least a bit awkward.

thkala
  • 84,049
  • 23
  • 157
  • 201
  • inotify is great. You'll have some special cases to take care of there though. Try watching a directory, listening to all events, open for example gedit, write something and save it to the dir you're watching. Interesting stuff is bound to happen. – manneorama Apr 11 '11 at 10:28
  • 1
    @manneorama: the worst problem with inotify is the lack of recursive watches. The userspace application has to set-up recursive watches itself... – thkala Apr 11 '11 at 12:12
1

Perhaps you should use inotify?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
1

Check out inotify (Linux-specific).

user470379
  • 4,879
  • 16
  • 21