Monday, May 1, 2017

Hack 4.20 Using File Functions to Get the Attributes of a File

SAS Programming Professionals,

Did you know that you can use a set of SAS file functions to get the attributes of a file?

The FILENAME, FOPEN, FOPTNUM, FOPTNAME, FINFO, and FCLOSE functions can be used in concert to read file attributes and store them in a SAS data set.  Here is an example:

data fileInfo(drop = rc fileid infonum i close);

length FileChar FileCharValue $60;

label FileChar = "File Characteristic"
      FileCharValue = "Value";




do i=1 to infonum;



proc print noobs label data=FileInfo;
title1 "File Characteristics";

We start the DATA step by specifying that the intermediate variables we use to get the file attributes are to be dropped.  Next, we set the length of the FileChar variable which holds the file characteristic and the FileCharValue variable which holds the value of a particular file characteristic.  We provide nice labels for both variables.

The FILENAME function creates a fileref (conveniently named FILEREF) for the particular file we want to examine.  The FOPEN function in the next line tells SAS to open the file associated with FILEREF.  SAS does so.

Next, we use the FOPTNUM option to determine how many variable characteristics SAS can find for this data set.  That number is stored in variable INFONUM, which will be used in the following DO loop.

The DO loop iterates from 1 to INFONUM, which is the total number of variable characteristics for the given data set.  The FOPTNAME option returns the name of a file characteristic and stores it in variable FileChar.  The FINFO function returns the value of that file characteristic and stores it in variable FileCharValue.  Once we have these two pieces of information (FileChar and FileCharValue), we OUTPUT them to the FileInfo SAS data set.

We end the data step by closing the file under investigation with the FCLOSE function.  And we display our good work with a simple PROC PRINT.  Here is what the report looks like:

File Characteristics

File Characteristic
File Size (bytes)
Last Modified
Create Time

Note that there were six file characteristics available to SAS; each of which can be found in our spiffy report.  This type of information can be invaluable when you need to write programs that read through directories looking for such things as particular data set types (e.g. XLSX), file sizes, and the dates files were last modified.

Best of luck in all your SAS endeavors!

(aka Michael A. Raithel)
Author of the new cult classic for computer programmers:  It Only Hurts When I Hit <ENTER>
Print edition: 
Kindle edition: 

The hack above is an excerpt from the book:  Did You Know That?  Essential Hacks for Clever SAS Programmers