简体   繁体   English

使用C,我如何知道何时创建文件?

[英]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. 我正在用C语言创建一个用于linux的程序,它在一段时间内每隔x秒扫描一个目录进行修改,但是我很难找到创建文件或目录的时间。 Here are a few options I considered: 以下是我考虑的几个选项:

  • Using the stat struct, check if the last status change and data modification timestamps are the same. 使用stat结构,检查上次状态更改和数据修改时间戳是否相同。 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. Similliar问题到最后的想法。

With that said, does anyone have any idea on how I can uniquely identify the creation of a file/directory? 话虽如此,有没有人知道如何唯一地识别文件/目录的创建?

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. POSIX没有规定将文件创建时间存储在文件系统中,如Windows和其他一些操作系统。 It only keeps the status change, access and modification times. 它只保留状态更改,访问和修改时间。 Most Unix filesystems do not store that information either. 大多数Unix文件系统也不存储该信息。

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. 其中一个原因是存在硬链接,因为文件时间戳存储在它们的inode中而不是存储在目录引用中。 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? 对于上午10点创建的文件,然后在上午11点硬链接到另一个目录,你会考虑创建时间是什么? 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, eg inotify on Linux and kqueue on FreeBSD and MacOS X... 您最好的,但不幸的是特定于操作系统的方法是使用您的平台中可用的任何框架来监视文件系统事件,例如Linux上的inotify和FreeBSD和MacOS X上的kqueue ......

EDIT: 编辑:

By the way, Ext4fs on Linux does store inode creation times ( crtime ). 顺便说一句,Linux上的Ext4fs确实存储了inode创建时间( crtime )。 Unfortunately getting to that information from userspace is still at least a bit awkward . 不幸的是,从用户空间获取该信息仍然至少有点尴尬

也许你应该使用inotify

查看inotify (特定于Linux)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM