# Defining a macro that writes content to an external file

I'd like to write a macro that has two arguments, filename and content. The macro - let's call it \mywrite - would write content to filename. The usage would look something like:

\mywrite{testfile.tex}{Hello, world!}


It would also be able to handle TeX commands, like:

\mywrite{testfile.tex}{%
\begin{itemize}
\item First item
\end{itemize}
}


The contents of testfile.tex would be the complete itemized environment.

I've tried using variations of fancyvrb, filecontents and directly using \write commands to no avail.

Is this possible?

My goal (for what it's worth) is to be able to write content to an external file that I call again from inside the current file.

• – Werner
Sep 6 '16 at 5:49

## 1 Answer

Before you can use \write you need to open a file using \newwrite and \openout. One way to do what you want in a macro is:

\documentclass{article}

\newwrite\mywriter% create a file handle
\newcommand\mywrite[2]{%
\immediate\openout\mywriter=#1% set the file name and open for writing
\immediate\write\mywriter{\unexpanded{#2}}% write without expanding
\immediate\closeout\mywriter% close file
}

\begin{document}

\mywrite{testfile.tex}{
\begin{itemize}
\item First item
\end{itemize}
}

\end{document}


This may not be what you want, however, because it ignores line breaks. A better approach would be to use the VerbatimOut environment from the fancyvrb package:

\documentclass{article}

\usepackage{fancyvrb}

\begin{document}

\begin{VerbatimOut}{testfile.tex}
\begin{itemize}
\item First item

\item Second
\end{itemize}
\end{VerbatimOut}

\end{document}


Neither of these approaches allows you to append to files, but if you are going to be writing lots of material to a given file then a macro/environment like this is probably not what you really want.

• the \unexpanded command is what I was missing from the \write approach (I knew about \immediate\openout, etc.). Seems to work well. Thanks. Your \VerbatimOut approach isn't what I was looking for - it lacks the macro aspect. Whenever I put it into a macro everything breaks down - even a macro that has no arguments. Sep 6 '16 at 10:04