Guest User

std::multimap for files

a guest
Feb 7th, 2016
156
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <cerrno>
  2. #include <cstring>
  3. #include <cstdlib>
  4. #include <cstdint>
  5. #include <iostream>
  6. #include <map>
  7. #include <string>
  8.  
  9. #include <unistd.h>
  10. #include <sys/types.h>
  11. #include <dirent.h>
  12. #include <sys/stat.h>
  13.  
  14. int main(int argc, char *argv[]) {
  15.     const char *dirname = argc > 1 ? argv[1] : nullptr;
  16.  
  17.     if (! dirname || chdir(dirname)) {
  18.         std::cerr << dirname << ": chdir(2) failed: "
  19.                   << strerror(errno) << std::endl;
  20.         exit(EXIT_FAILURE);
  21.     }
  22.  
  23.     DIR *dir = opendir(dirname);
  24.     if (! dir) {
  25.         std::cerr << dirname << ": opendir(3) failed: "
  26.                   << strerror(errno) << std::endl;
  27.         exit(EXIT_FAILURE);
  28.     }
  29.  
  30.     std::multimap<off_t, std::string> files;
  31.     for (dirent *entry = readdir(dir); entry; entry = readdir(dir)) {
  32.         struct stat stats;
  33.         if (stat(entry->d_name, &stats)) {
  34.             std::cerr << entry->d_name << ": stat(2) failed: "
  35.                       << strerror(errno) << std::endl;
  36.         }
  37.  
  38.         files.insert(std::make_pair(stats.st_size, std::string(entry->d_name)));
  39.     }
  40.     if (errno) {
  41.         std::cerr << dirname << ": readdir(3) failed: "
  42.                   << strerror(errno) << std::endl;
  43.     }
  44.     closedir(dir);
  45.  
  46.     for (auto entry : files) {
  47.         std::cout << entry.first << "\t" << entry.second << std::endl;
  48.     }
  49.  
  50.     return EXIT_SUCCESS;
  51. }
RAW Paste Data