simple_ls.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // simple_ls program -------------------------------------------------------//
  2. // Copyright Jeff Garland and Beman Dawes, 2002
  3. // Use, modification, and distribution is subject to the Boost Software
  4. // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. // See http://www.boost.org/libs/filesystem for documentation.
  7. #define BOOST_FILESYSTEM_VERSION 3
  8. // As an example program, we don't want to use any deprecated features
  9. #ifndef BOOST_FILESYSTEM_NO_DEPRECATED
  10. # define BOOST_FILESYSTEM_NO_DEPRECATED
  11. #endif
  12. #ifndef BOOST_SYSTEM_NO_DEPRECATED
  13. # define BOOST_SYSTEM_NO_DEPRECATED
  14. #endif
  15. #include <boost/filesystem/operations.hpp>
  16. #include <boost/filesystem/directory.hpp>
  17. #include <boost/filesystem/path.hpp>
  18. #include <iostream>
  19. namespace fs = boost::filesystem;
  20. int main(int argc, char* argv[])
  21. {
  22. fs::path p(fs::current_path());
  23. if (argc > 1)
  24. p = fs::system_complete(argv[1]);
  25. else
  26. std::cout << "\nusage: simple_ls [path]" << std::endl;
  27. unsigned long file_count = 0;
  28. unsigned long dir_count = 0;
  29. unsigned long other_count = 0;
  30. unsigned long err_count = 0;
  31. if (!fs::exists(p))
  32. {
  33. std::cout << "\nNot found: " << p << std::endl;
  34. return 1;
  35. }
  36. if (fs::is_directory(p))
  37. {
  38. std::cout << "\nIn directory: " << p << "\n\n";
  39. fs::directory_iterator end_iter;
  40. for (fs::directory_iterator dir_itr(p);
  41. dir_itr != end_iter;
  42. ++dir_itr)
  43. {
  44. try
  45. {
  46. if (fs::is_directory(dir_itr->status()))
  47. {
  48. ++dir_count;
  49. std::cout << dir_itr->path().filename() << " [directory]\n";
  50. }
  51. else if (fs::is_regular_file(dir_itr->status()))
  52. {
  53. ++file_count;
  54. std::cout << dir_itr->path().filename() << "\n";
  55. }
  56. else
  57. {
  58. ++other_count;
  59. std::cout << dir_itr->path().filename() << " [other]\n";
  60. }
  61. }
  62. catch (const std::exception & ex)
  63. {
  64. ++err_count;
  65. std::cout << dir_itr->path().filename() << " " << ex.what() << std::endl;
  66. }
  67. }
  68. std::cout << "\n" << file_count << " files\n"
  69. << dir_count << " directories\n"
  70. << other_count << " others\n"
  71. << err_count << " errors\n";
  72. }
  73. else // must be a file
  74. {
  75. std::cout << "\nFound: " << p << "\n";
  76. }
  77. return 0;
  78. }