# using \newcommand with \immediate\write inside beamer

I'm trying to write some strings to an external file using the \immediate\write as in the MWE below

\documentclass[a4paper,9pt]{beamer}
\begin{document}

\begin{frame}[plain] %< comment out for article

\newcommand{\createtexfile}[1]{%
\newwrite\file
\immediate\openout\file=output.tex
\immediate\write\file{\string\textbf{foo bar} }
\immediate\write\file{\string #1}
\immediate\closeout\file
}

\createtexfile{some text}

\end{frame} %< comment out for article
\end{document}


which should output:

> cat output.tex

\textbf{foo bar}
some text


If I run this using 'article' as a document class (frame should be commented out) it compiles without errors. When using the 'beamer' documentclass I get the following error:

! Illegal parameter number in definition of \iterate. 1 l.17 \end{frame} %< comment out for article You meant to type ## instead of #, right? Or maybe a } was forgotten somewhere earlier, and things are all screwed up? I'm going to assume that you meant ##.

Does anybody else get this error as well? and if so, any ideas how to get around it? I would appreciate you inputs.

• don't define the command inside the frame and always never have the \newwrite inside a macro you just want to do that once, in the preamble. You are also missing % from ends of lines. Aug 1, 2018 at 18:19

Don't define the command inside the frame, define it in the preamble.

Also, always (not just in beamer) never have the \newwrite inside a macro you just want to do that once, in the preamble.

You are also missing % from ends of lines.

Just for completion, taking the answer from David Carlisle, this is how should be implemented.

\documentclass[a4paper,9pt]{beamer}

\newwrite\file %<-

\newcommand{\createtexfile}[1]{%
\immediate\openout\file=output.tex
\immediate\write\file{\string\textbf{foo bar} }%<-
\immediate\write\file{\string #1}%<-
\immediate\closeout\file%<-
}

\begin{document}

\begin{frame}[plain] %< comment out for article

\createtexfile{some text}

\end{frame} %< comment out for article
\end{document}