HOW CAN I CHECK IF A DIRECTORY ALREADY EXISTS AND IF NOT, CREATE IT?

The macro works by using the %SYSFUNC macro function to check to see if a filename assigns correctly and if so puts out a message to the SAS log to say the directory exists. If the fileref does not assign correctly, due to the directory not existing, then the following code uses the %SYSEXEC macro function to create a new directory using the (dir =) parameter passed to the macro.

To demonstrate this, in this example we check for a directory that we know exists, c:\temp and then a directory that may not exist, c:\temp\sascode.

%macro chk_dir(dir=) ;
   options noxwait;
   %local rc fileref ;
   %let rc = %sysfunc(filename(fileref,&dir)) ;
   %if %sysfunc(fexist(&fileref))  %then
      %put NOTE: The directory "&dir" exists ;
   %else
     %do ;
         %sysexec md   &dir ;
         %put %sysfunc(sysmsg()) The directory has been created. ;
   %end ;
   %let rc=%sysfunc(filename(fileref)) ;
%mend chk_dir ;

%chk_dir(dir=c:\temp) ;    %*   <==  your directory specification goes here ;
%chk_dir(dir=c:\temp\sascode)  

Note: The above code has been tested using SAS 8.2 on the Windows operating system.

Did you find this page useful?

If you have any comments or questions, feel free to contact us.




0845 402 9907