Macros for SAS Application Developers
https://github.com/sasjs/core
mcf_string2file.sas
Go to the documentation of this file.
1 /**
2  @file
3  @brief Adds a string to a file
4  @details Creates an fcmp function for appending a string to an external file.
5  If the file does not exist, it is created.
6 
7  The function itself takes the following (positional) parameters:
8 
9  | PARAMETER | DESCRIPTION |
10  |------------|-------------|
11  | filepath $ | full path to the file|
12  | string $ | string to add to the file |
13  | mode $ | mode of the output - either APPEND (default) or CREATE |
14 
15  It returns 0 if successful, or -1 if an error occured.
16 
17  Usage:
18 
19  %mcf_string2file(wrap=YES, insert_cmplib=YES)
20 
21  data _null_;
22  rc=mcf_string2file(
23  "%sysfunc(pathname(work))/newfile.txt"
24  , "This is a test"
25  , "CREATE");
26  run;
27 
28  data _null_;
29  infile "%sysfunc(pathname(work))/newfile.txt";
30  input;
31  putlog _infile_;
32  run;
33 
34  @param [out] wrap= (NO) Choose YES to add the proc fcmp wrapper.
35  @param [out] lib= (work) The output library in which to create the catalog.
36  @param [out] cat= (sasjs) The output catalog in which to create the package.
37  @param [out] pkg= (utils) The output package in which to create the function.
38  Uses a 3 part format: libref.catalog.package
39  @param [out] insert_cmplib= DEPRECATED - The CMPLIB option is checked and
40  values inserted only if needed.
41 
42  <h4> SAS Macros </h4>
43  @li mcf_init.sas
44 
45  <h4> Related Programs </h4>
46  @li mcf_stpsrv_header.test.sas
47  @li mp_init.sas
48 
49 **/
50 
51 %macro mcf_string2file(wrap=NO
52  ,insert_cmplib=DEPRECATED
53  ,lib=WORK
54  ,cat=SASJS
55  ,pkg=UTILS
56 )/*/STORE SOURCE*/;
57 %local i var cmpval found;
58 %if %mcf_init(mcf_string2file)=1 %then %return;
59 
60 %if &wrap=YES %then %do;
61  proc fcmp outlib=&lib..&cat..&pkg;
62 %end;
63 
64 function mcf_string2file(filepath $, string $, mode $);
65  if mode='APPEND' then fmode='a';
66  else fmode='o';
67  length fref $8;
68  rc=filename(fref,filepath);
69  if (rc ne 0) then return( -1 );
70  fid = fopen(fref,fmode);
71  if (fid = 0) then return( -1 );
72  rc=fput(fid, string);
73  rc=fwrite(fid);
74  rc=fclose(fid);
75  rc=filename(fref);
76  return(0);
77 endsub;
78 
79 
80 %if &wrap=YES %then %do;
81  quit;
82 %end;
83 
84 /* insert the CMPLIB if not already there */
85 %let cmpval=%sysfunc(getoption(cmplib));
86 %let found=0;
87 %do i=1 %to %sysfunc(countw(&cmpval,%str( %(%))));
88  %let var=%scan(&cmpval,&i,%str( %(%)));
89  %if &var=&lib..&cat %then %let found=1;
90 %end;
91 %if &found=0 %then %do;
92  options insert=(CMPLIB=(&lib..&cat));
93 %end;
94 
95 %mend mcf_string2file;