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

后端 未结 6 880
别跟我提以往
别跟我提以往 2021-02-12 16:35

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 c

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-12 17:25

    There is no language-specific way to do this, however the OS provides the required functionality. In a unix system, the stat function is what you need. There is an equivalent _stat function provided for windows under Visual Studio.

    So here is code that would work for both:

    #include 
    #include 
    #ifndef WIN32
    #include 
    #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_mtime;
        ...
    }
    

提交回复
热议问题