User:TobyDunn/BlogEntry: 2007 May 10 22:22:27 EDT
From sasCommunity
[edit] Part 2 of 3 "A Macro That Reads All Files In A Directory"
%Macro GetFiles( FilePath= ) ;
%Local MyFile FileName DSID I Close ;
%Let MyFile = MyDir ;
%Let FileName = %SysFunc( FileName( MyFile , &FilePath ) ) ;
%Let DSID = %SysFunc( DOpen( &MyFile ) ) ;
%Do I = 1 %To %SysFunc( DNum( &DSID ) ) ;
%SysFunc( DRead( &DSID , &I ) )
%End ;
%Let Close = %SysFunc( DClose( &DSID ) ) ;
%Mend GetFiles ;
We need to allocate the directory to a file statement. To do this and keep it all in pure macro code, we use the FileName function. Like the last macro, we need to open the directory so that we can read all the file names. In the last macro, we used the Open function which works on SAS datasets, not directories. So SAS has the DOpen to open a directory. We need to count the number of files in the directory and for that we have Dnum, which returns the number of files in the directory. Next we use the DRead function to read a file name. Finally, we use the DClose to close the directory.
Next we will see how to have a macro write data to an external file.
