大佬教程收集整理的这篇文章主要介绍了c – 使用stat来检测文件是否存在(慢?),大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
//... do something struct stat buf; while(stat("myfile.txt",&buf)) sleep(1); //... do something else
但是,您的代码有一点问题.每次检查尚不存在的文件时,它会使进程休眠一秒钟.为避免这种情况,您必须按照jerry Coffin的建议使用inotify API,以便在您等待的文件存在时通过内核获得通知.请记住,如果文件已存在,inotify不会通知您,因此实际上您需要同时使用“access”和“inotify”来避免在创建文件后立即开始查看文件时出现竞争情况.
没有更好或更快的方法来检查文件是否存在.如果您的文件浏览器仍然显示该文件比该程序检测到的文件稍快,那么Greg Hewgill关于重命名的想法可能正在发生.
下面是一个C代码示例,用于设置inotify监视,检查文件是否已存在并等待它:
#include <cstdio> #include <cString> #include <String> #include <unistd.h> #include <sys/inotify.h> int main () { const std::string directory = "/tmp"; const std::string filename = "test.txt"; const std::string fullpath = directory + "/" + filename; int fd = inotify_init (); int watch = inotify_add_watch (fd,directory.c_str (),IN_MODIFY | IN_CREATE | IN_MOVED_TO); if (access (fullpath.c_str (),F_OK) == 0) { printf ("File %s exists.\n",fullpath.c_str ()); return 0; } char buf [1024 * (sizeof (inotify_event) + 16)]; ssize_t length; bool isCreated = false; while (!isCreated) { length = read (fd,buf,sizeof (buf)); if (length < 0) break; inotify_event *event; for (size_t i = 0; i < static_cast<size_t> (length); i += sizeof (inotify_event) + event->len) { event = reinterpret_cast<inotify_event *> (&buf[i]); if (event->len > 0 && filename == event->Name) { printf ("The file %s was created.\n",event->Name); isCreated = true; break; } } } inotify_rm_watch (fd,watch); close (fd); }
以上是大佬教程为你收集整理的c – 使用stat来检测文件是否存在(慢?)全部内容,希望文章能够帮你解决c – 使用stat来检测文件是否存在(慢?)所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。