Published on :
Macro INTERNAL_CREATION

Recursive directory creation macro

This code is also available in: Deutsch Español Français
Attention : This code requires administrator privileges.
The `%mkdir` macro takes a directory path as a parameter and creates it recursively using the `md` system command. It checks for the existence of each path segment and creates them if necessary. The macro handles long file names and displays messages upon success or failure of directory creation. The use of `%sysexec` classifies it as an administration script because it directly interacts with the operating system.
Data Analysis

Type : INTERNAL_CREATION


The macro interacts directly with the file system to create directories and does not process internal or external SAS datasets. The main action is the modification of the system environment.

1 Code Block
MACRO %mkdir
Explanation :
This block defines the `%mkdir` macro. It takes a directory path and an optional delimiter. The macro parses the path segment by segment. For each segment, it reconstructs a partial path and checks if the directory exists with `%sysfunc(fileexist)`. If a directory does not exist, the `md` system command is executed via `%sysexec` to create it. A track is kept to detect if a creation has occurred (`&op = 1`). In case of failure to create a directory (re-checked by `fileexist`), the process is interrupted and an error message is set. Finally, a success or failure message is displayed. The use of `%sysexec` implies that the SAS environment must have the necessary permissions to execute shell commands.
Copied!
1 %macro mkdir(path,dlm=\\%);
2
3 %let msg = The path &path was successfully created.;
4
5 %let pos = 1;
6 %let token = %scan(&path, &pos, &dlm);
7 %let segment =;
8 %let delim =;
9 %let op =;
10
11
12 %DO %while (&token ne);
13
14 %let segment = &segment.&delim.&token;
15 %let delim = \\;
16 %* put &segment;
17
18 %let pos = %eval(&pos + 1);
19 %let token = %scan(&path, &pos, &dlm);
20
21 %IF %sysfunc(fileexist(&segment)) eq 0 %THEN %DO;
22 %sysexec md &segment;
23 %* put ERRORCODE &sysrc;
24 %let op = 1;
25
26 /* if the operation failed, display approptiate message
27 and abort the program */
28 %IF %sysfunc(fileexist(&segment)) eq 0 %THEN %DO;
29 %let token =;
30 %let msg = Invalid path name, directory will not be
31created.; %END;
32
33 %END;
34 %END;
35
36 %IF &op = 1 %THEN %put MKDIR: &msg;
37 /*
38 %else %put MKDIR: The path &path does already exist;
39 */
40 %mend;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.
Copyright Info : Subject: SOLUTION: Create a directory from SAS Date: 05/22/2000 Author: Benjamin Guralnik <guralnik @BEZEQINT.NET>Thanks, Jim.