Production Ready Macros for SAS Application Developers
https://github.com/sasjs/core
mp_tree.sas
Go to the documentation of this file.
1 /**
2  @file
3  @brief Recursively scans a directory tree to get all subfolders and content
4  @details
5  Usage:
6 
7  %mp_tree(dir=/tmp, outds=work.tree)
8 
9  Credits:
10 
11  * Roger Deangelis, https://communities.sas.com/t5/SAS-Programming/listing-all-files-within-a-directory-and-subdirectories/m-p/332616/highlight/true#M74887
12  * Tom, https://communities.sas.com/t5/SAS-Programming/listing-all-files-of-all-types-from-all-subdirectories/m-p/334113/highlight/true#M75419
13 
14 
15  @param dir= Directory to be scanned (default=/tmp)
16  @param outds= Dataset to create (default=work.mp_tree)
17 
18  @returns outds contains the following variables:
19 
20  - `dir`: a flag (1/0) to say whether it is a directory or not. This is not
21  reliable - folders that you do not have permission to open will be flagged
22  as directories.
23  - `ext`: file extension
24  - `filename`: file name
25  - `dirname`: directory name
26  - `fullpath`: directory + file name
27 
28  @version 9.2
29 **/
30 
31 %macro mp_tree(dir=/tmp
32  ,outds=work.mp_tree
33 )/*/STORE SOURCE*/;
34 
35 data &outds ;
36  length dir 8 ext filename dirname $256 fullpath $512 ;
37  call missing(of _all_);
38  fullpath = "&dir";
39 run;
40 
41 %local sep;
42 %if &sysscp=WIN or &SYSSCP eq DNTHOST %then %let sep=\;
43 %else %let sep=/;
44 
45 data &outds ;
46  modify &outds ;
47  retain sep "&sep";
48  rc=filename('tmp',fullpath);
49  dir_id=dopen('tmp');
50  dir = (dir_id ne 0) ;
51  if dir then dirname=fullpath;
52  else do;
53  filename=scan(fullpath,-1,sep) ;
54  dirname =substrn(fullpath,1,length(fullpath)-length(filename));
55  if index(filename,'.')>1 then ext=scan(filename,-1,'.');
56  end;
57  replace;
58  if dir then do;
59  do i=1 to dnum(dir_id);
60  fullpath=cats(dirname,sep,dread(dir_id,i));
61  output;
62  end;
63  rc=dclose(dir_id);
64  end;
65  rc=filename('tmp');
66 run;
67 
68 %mend;