Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C, how can I know when a file is created?

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?

like image 581
Mr eskimo Avatar asked Nov 20 '25 22:11

Mr eskimo


2 Answers

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.

like image 168
thkala Avatar answered Nov 23 '25 13:11

thkala


Perhaps you should use inotify?

like image 27
Bill Lynch Avatar answered Nov 23 '25 13:11

Bill Lynch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!