C++:boost file system to return a list of files older than a specific time

随声附和 提交于 2019-12-19 15:40:28

问题


I am using the Boost::FileSystem library with C++ running under Linux platform and I have a question following:

I would like to have a list of files which are modified older than a given date time. I don't know whether the boost::FileSystem offer such a method as:

vector<string> listFiles = boost::FileSystem::getFiles("\directory", "01/01/2010 12:00:00");

If yes, could you please provide sample code?


回答1:


Boost::filesystem doesn't offer a function exactly like that. But you can use this:

http://www.boost.org/doc/libs/1_45_0/libs/filesystem/v3/doc/reference.html#last_write_time

as a basis to write your own. Here is some sample code using last_write_time:

#include <boost/filesystem/operations.hpp>
#include <ctime>
#include <iostream>

int main( int argc , char *argv[ ] ) {
   if ( argc != 2 ) {
      std::cerr << "Error! Syntax: moditime <filename>!\n" ;
      return 1 ;
   }
   boost::filesystem::path p( argv[ 1 ] ) ;
   if ( boost::filesystem::exists( p ) ) {
      std::time_t t = boost::filesystem::last_write_time( p ) ;
      std::cout << "On " << std::ctime( &t ) << " the file " << argv[ 1 ] 
     << " was modified the last time!\n" ;
      std::cout << "Setting the modification time to now:\n" ;
      std::time_t n = std::time( 0 ) ;
      boost::filesystem::last_write_time( p , n ) ; 
      t = boost::filesystem::last_write_time( p ) ;
      std::cout << "Now the modification time is " << std::ctime( &t ) << std::endl ;
      return 0 ;
   } else {
      std::cout << "Could not find file " << argv[ 1 ] << '\n' ;
      return 2 ;
   }
}



回答2:


You can use a std::map(last_write_time, fileName) to store the file last modified time and the absolute file path and the do an in-order traversal to sort the data.



来源:https://stackoverflow.com/questions/4279164/cboost-file-system-to-return-a-list-of-files-older-than-a-specific-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!