Created
July 30, 2018 11:38
-
-
Save schdub/132e1652ec1c86504d8b01e0d030b3c6 to your computer and use it in GitHub Desktop.
Only 10 recent logs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <dirent.h> | |
#include <sys/stat.h> | |
#include <string> | |
#include <cstring> | |
#include <map> | |
template<typename Key, typename T> | |
void flipMap(const std::map<Key, T> & source, | |
std::multimap<T, Key, std::greater<T>> & result) { | |
typedef std::map<Key, T> source_type; | |
typedef typename source_type::const_iterator source_iterator; | |
for (source_iterator i = source.begin(), end = source.end(); i != end; ++i) { | |
result.insert(std::make_pair((*i).second, (*i).first)); | |
} | |
} | |
int main() { | |
char g_path[] = "/home/schdub/src/work/bmc-acr122/app/logs"; | |
DIR *theFolder = ::opendir(g_path); | |
if (theFolder == NULL) | |
return 1; | |
struct dirent *next_file; | |
char filepath[256]; | |
std::multimap<time_t, std::string, std::greater<time_t>> logs_sorted; { | |
std::map<std::string, time_t> logs; | |
while ((next_file = ::readdir(theFolder)) != NULL) { | |
size_t len = strlen(next_file->d_name); | |
const char * ext = &next_file->d_name[len-4]; | |
if (len <= 4 || ::strcmp(ext, ".log")) continue; | |
// build the path for each file in the folder | |
::sprintf(filepath, "%s%s%s", g_path, "/", next_file->d_name); | |
struct stat info; | |
if (::stat(filepath, &info) == 0) { | |
logs[std::string(filepath)] = info.st_mtim.tv_sec; | |
std::cout << next_file->d_name << " " << info.st_mtim.tv_sec << std::endl; | |
} | |
} | |
::closedir(theFolder); | |
flipMap(logs, logs_sorted); | |
} | |
unsigned cnt = 0; | |
unsigned required = 10; | |
for (auto i = logs_sorted.begin(), end = logs_sorted.end(); i != end; ++i, ++cnt) { | |
std::cout << (*i).second << " " << (*i).first << std::endl; | |
if (cnt < required) continue; | |
// ::remove((*i).second.c_str()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment