How to determine if the external file is empty in SAS?

The macro checks determine if the external file is empty in SAS. An error message is written to the log if it doesn’t exist. SAS attempts to read the data from the file if the file exists. 

Data access functions like FOPEN, FREAD, and FGET are used to retrieve the data. The message is written to the log if there is no data to be read from the file.

%macro check_empty(outfile);
   %let filrf=myfile;
   %if %sysfunc(fileexist(&outfile)) %then %do;
   %let rc=%sysfunc(filename(filrf,&outfile));
   %let fid=%sysfunc(fopen(&filrf));
    %if &fid > 0 %then %do;
     %let rc=%sysfunc(fread(&fid));
     %let rc=%sysfunc(fget(&fid,mystring));
      %if &rc = 0 %then %put &mystring;
      %else %put file is empty;
     %let rc=%sysfunc(fclose(&fid));
  %let rc=%sysfunc(filename(filrf));
  %else %put file does not exist;
  %mend check_empty;


The %LET statement is used to create a macro variable named &filrf that will contain the fileref name.

The %IF statement with the FILEEXIST function verifies that the file passed to the macro exists.

The FILENAME function associates a fileref with the file passed into the macro named &outfile.

We Use the FOPEN function to open that file and assign a file identifier value to the macro variable &fid.

To ensure that the FGET function was successful, we use the %IF statement. If the operation were successful, FGET would return 0, and we use a %PUT statement to write the contents of the variable named &mystring to the log.

The %PUT statement will write an empty message to the log if the %IF condition is false.

Every week we'll send you SAS tips and in-depth tutorials



Subhro provides valuable and informative content on SAS, offering a comprehensive understanding of SAS concepts. We have been creating SAS tutorials since 2019, and 9to5sas has become one of the leading free SAS resources available on the internet.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This Post Has 2 Comments

  1. Anand

    Hi Subro
    your Blog is super for SAS beginners and experienced
    Could you please points for below interview question
    Q1.) What is the difference between implicit pass thru query and explicit pass thru query which is the best in terms of optimize the code and which functions are work for both?

  2. Subhro

    Hi Anand,
    In the implicit pass-thru, SAS automatically converts the SQL code so that that the database can understand. You will not be able to write SQL-specific functions using implicit pass-thru. In explicit pass-thru, you write the SQL query in the SQL dialect understood by the database. Generally, Explicit pass-thu is more optimized because you can write queries that are tailored to the specific database engine you are using, and you can use database-specific syntax and functions for better performance.