Mr. Nicky Mr. Nicky - 25 days ago 15
C++ Question

C++ How to check the last modified time of a file

I'm caching some information from a file and I want to be able to check periodically if the file's content has been modified so that I can read the file again to get the new content if needed.

That's why I'm wondering if there is a way to get a file's last modified time in C++.

Answer

There is no language-specific way to do this: however the OS provides the required functionality.

If you're using a unix system, the the stat call is what you need. There is an equivalent _stat call provided for windows under Visual Studio. So here is code that would work for both:

   #include <sys/types.h>
   #include <sys/stat.h>
   #ifndef WIN32
   #include <unistd.h>
   #endif

   #ifdef WIN32
   #define stat _stat
   #endif

   auto filename = "/path/to/file";
   struct stat result;
   if(stat(filename.c_str(), &result)==0)
   {
       auto mod_time = result.st_mtim;
       ...
   }
Comments