-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursive_boost_ls.cpp
More file actions
88 lines (69 loc) · 2.53 KB
/
recursive_boost_ls.cpp
File metadata and controls
88 lines (69 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* C++ program to list all non-directory files in provided path (Recursive implementation)
* Usage: ./recursive_boost_ls path
* e.g. ./recursive_boost_ls A/
*/
#include <iostream>
#include <iterator>
#include <algorithm>
#include <boost/filesystem.hpp>
#include <vector>
using namespace std;
using namespace boost::filesystem;
void listFilesInDirectory ( directory_iterator );
int main (int argc, char* argv[])
{
// Exit the program in case of missing argument
if ( argc < 2 )
{
cout << "Usage: boost_ls path\n" ;
return 1;
}
path p ( argv[1] );
// Exit the program if argument is not a valid directory path
if ( ! exists(p) )
{
cout << p.string() << " directory does not exist" << endl;
return 1;
}
// Exit the program if argument is not a directory
if ( ! is_directory(p) )
{
cout << p.string() << " is not a directory" << endl;
return 1;
}
cout << "Entered path is " << p.string() << endl;
// directory_iterator object initialized for current directory
directory_iterator dir_iter(p);
cout << "All files in this path are " << endl;
// Recursively list all the files in directory and traverse the sub-directories
listFilesInDirectory ( dir_iter );
}
void listFilesInDirectory ( directory_iterator dir_iter )
{
vector<path> sortedList;
// Copy all files in present directory from dir_iter to sortedList vector
copy ( dir_iter, directory_iterator(), back_inserter(sortedList) );
// Sort the vector to order files and directories
sort ( sortedList.begin(), sortedList.end() );
// Reverse the vector to bring all files before directories since we want to print
// files in current directory first and then traverse to sub-directories
reverse( sortedList.begin(), sortedList.end() );
// Traverse through all files and directories in present directory
for (vector<path>::const_iterator it (sortedList.begin()), it_end(sortedList.end()); it != it_end; ++it)
{
// If present directory contains a directory, recurse
if ( is_directory( *it ) )
{
//cout << "Directory " << curr_dir_iter->path().filename() << endl;
directory_iterator next_dir_iter( *it );
listFilesInDirectory ( next_dir_iter );
}
// If present directory contains a file print it out
else if ( is_regular_file( *it ) )
{
path temp_path(*it);
cout << temp_path.relative_path().string() << endl;
}
}
}