代码之家  ›  专栏  ›  技术社区  ›  PeteUK

如何比较TimeIt和STD::文件系统::FielyTimeType类型

  •  5
  • PeteUK  · 技术社区  · 8 年前

    我正在转换一些代码 boost::filesystem std::filesystem . 以前使用的代码 boost::filesystem::last_write_time() 它返回一个 time_t 所以直接比较 Timet 我已经持有的东西是微不足道的。顺便说一下,这个 Timet 我认为是 从长期保存的文件内容中读取 ,所以我坚持使用“从Unix时代开始的时间”类型。

    std::filesystem::last_write_time 返回 std::filesystem::file_time_type . 有便携式转换方法吗 file_time_type 到A Timet 或者可以方便地比较这两个对象?

    #include <ctime>
    #include <filesystem>
    
    std::time_t GetATimeInSecondsSince1970Epoch()
    {
        return 1207609200;  // Some time in April 2008 (just an example!)
    }
    
    int main()
    {
        const std::time_t time = GetATimeInSecondsSince1970Epoch();
        const auto lastWriteTime = std::filesystem::last_write_time("c:\\file.txt");
    
        // How to portably compare time and lastWriteTime?
    }
    

    编辑 :请注意 sample code at cppreference.com for last_write_time 声明它假设时钟是 std::chrono::system_clock 它实现了 to_time_t 功能。这种假设并不总是正确的,也不在我的平台上(VS2017)。

    3 回复  |  直到 7 年前
        1
  •  3
  •   SergeyA    8 年前

    你链接的文章展示了如何做到这一点:通过 to_time_t 相应的成员 clock file_time_type .

    从您自己的链接复制粘贴:

    auto ftime = fs::last_write_time(p);
    std::time_t cftime = decltype(ftime)::clock::to_time_t(ftime); 
    

    如果你的站台不给你 system_clock 作为时钟 文件时间类型 比没有便携式解决方案(至少,C++ 20时) 文件时间类型 时钟是标准化的)。在这之前,你必须弄清楚它实际上是什么时钟,然后适当地安排时间 duration_cast 还有朋友。

        2
  •  4
  •   Howard Hinnant    8 年前

    FWW,当C++ 20到达这里时,便携式解决方案将是:

    clock_cast<file_clock>(system_clock::from_time_t(time)) < lastWriteTime
    

    这将转换 time_t 进入之内 file_time 反之亦然。这种方法的优点是 文件时间 通常具有比 Timet . 转换 文件时间 Timet 会在转换过程中降低精度,从而可能导致比较不准确。

        3
  •  0
  •   S.Clem    7 年前

    我也遇到了同样的问题,我用Visual Studio专用代码解决了这个问题。

    对于vs,我使用 _wstati64 功能( w 对于宽字符,因为Windows用UTF16)和 wstring 转换 path 班级。

    整个过程都集中在这个函数中:

    #if defined ( _WIN32 )
    #include <sys/stat.h>
    #endif
    
    std::time_t GetFileWriteTime ( const std::filesystem::path& filename )
    {
        #if defined ( _WIN32 )
        {
            struct _stat64 fileInfo;
            if ( _wstati64 ( filename.wstring ().c_str (), &fileInfo ) != 0 )
            {
                throw std::runtime_error ( "Failed to get last write time." );
            }
            return fileInfo.st_mtime;
        }
        #else
        {
            auto fsTime = std::filesystem::last_write_time ( filename );
            return decltype ( fsTime )::clock::to_time_t ( fsTime );
        }
        #endif
    }
    
    推荐文章