Listing Files in a Directory
There are at least two different approaches in SAS to listing the contents of a directory. The easy way is to tell SAS to issue an operating system command; however, on some sites this facility is disabled for security reasons. In such a situation, it is still possible to list the contents of a directory, but slightly more coding effort is needed.
Here is an example of doing it the easy way under Windows:
This program writes to the SAS log a list of all the ".xlsx" files in Windows directory C:temp. The core of it is the FILENAME PIPE statement, which contains a Windows command to be issued. In this case, there are actually three Windows commands, concatenated using the Windows "&&" operator.
An INFILE statement makes the output from this Windows command sequence available to the data step. The INPUT statement reads one line of it at a time into the _INFILE_ buffer, and a subsetting IF allows through only filenames where the extension is ".xlsx".
However, running the above code might result in error message along the lines of "Insufficient authorization to access PIPE". If this happens, you could try talking sweetly to your system administrator, asking for "X commands" to be allowed - or you could try some alternative code.
This program produces exactly the same results as the previous one, but will work even if SAS has been configured so that it is not allowed to issue external commands. It has the further benefit that it should work regardless of the host operating system. This data step uses four SAS functions to process the directory:
- DOPEN to open the directory, and get a "directory ID" for it.
- DNUM to count the files in it
- DREAD to read the name of each file
- DCLOSE to close the directory.