# Re: st: Writing macro contents to a file

 From jpitblado@stata.com (Jeff Pitblado, Stata Corp.) To statalist@hsphsun2.harvard.edu Subject Re: st: Writing macro contents to a file Date Wed, 25 Jun 2003 12:43:27 -0500

Roger Newson <roger.newson@kcl.ac.uk> asks about outputting text to files with
the -file- command:

> A query re writing the contents of a Stata macro to a file. I have been
> trying to do this by using -file write-, with a file open for writing as an
> ASCII file, as I have not found a way of writing  macro contents to a
> binary file. For instance, if the macro is a local macro named -linecur-,
> and the file handle is stored in another local macro named -uhandle-, then
> I might write
>
> file write uhandle'  "linecur'"' _n
>
> to write the contents of the macro -linecur- to the file whose handle is
> stored in -uhandle-.
>
> There is one problem with this approach, namely that it involves quoting.
> When Stata quotes a string, it substitutes each occurrence of the substring
> \\ (double backslash) with a \ (single backslash). This will cause problems
> if my macro -linecur- contains double backslashes. For instance, if
> -linecur- contains the string
>
> \textit{Make}&\textit{Weight}\\
>
> then the -file- command shown above will write, to the file, the string
>
> \textit{Make}&\textit{Weight}\
>
> ...
>
> Why should this be the case? And does anybody out there know of a better
> way to output the contents of a macro to a file? I am using Stata 8 under
> Windows 98 SE. The full log of what I did is listed below.
>
> ...

I believe -macval()- will solve the problem.  The second -file write- command
below uses -macval()- to output the contents of -linecur'- to the file.

***** BEGIN:
. tempname uhandle

. local linecur "\textit{Make}&\textit{Weight}\\\\"

. mac li _linecur
_linecur:       \textit{Make}&\textit{Weight}\\

. file open uhandle' using nutz.txt, write text replace

. file write uhandle'  "linecur'"' _n

. file write uhandle'  "macval(linecur)'"' _n

. file close uhandle'

. type nutz.txt
\textit{Make}&\textit{Weight}\
\textit{Make}&\textit{Weight}\\

***** END:

--Jeff