User:TobyDunn/BlogEntry: 2008 April 06 03:06:37 EDT

From sasCommunity

Jump to: navigation, search

[edit] Part 3 of 3 "A Macro That Creates And Writes Data To A Text File"

    %Macro Write2File( FileOut= ) ;
    %Local File FileName FileId I Text Write Close ;

    %Let File     = MyFile ;

    %Let FileName = %SysFunc( FileName( File , &FileOut ) ) ;

    %Let FileId   = %SysFunc( FOpen( &File , O , , P    ) ) ;

    %Do I = 1 %To 50 ;
      %Let Text   = %SysFunc( FPut( &FileId , &I        ) ) ;
      %Let Write  = %SysFunc( FWrite( &FileId           ) ) ;
    %End ;

    %Let Close    = %SysFunc( FClose( &FileId           ) ) ;

    %Mend Write2File ;

%Write2File( FileOut = C:\Documents and Settings\Toby Dunn\Desktop\ABC.TXT ) 


The Write2File Macro is a simple example of how to have a macro create and write text to a file.

%Let File = MyFile ; Creates a alais for the file, it is just like the alias one would use in a normal FileName statement in any SAS program.

%Let FileName = %SysFunc( FileName( File , &FileOut ) ) ; Alocates a FileName Statement with the alias in the macro variable File. The FileOut macro variable contains the path and the name of the output file with its extension.


%Let FileId = %SysFunc( FOpen( &File , O , , P ) ) ; Opens the file so that the values can be written to it. Incedently it is also step where the file gets physically created.


%Let Text = %SysFunc( FPut( &FileId , &I ) ) ; Creates the text to be written.

%Let Write = %SysFunc( FWrite( &FileId ) ) ; Physically writes the text in the macro variable Text to the created file.


%Let Close = %SysFunc( FClose( &FileId ) ) ; Closes the created file.

Personal tools