I wouldn't reinvent the wheel. ;-)
\documentclass{article}
\usepackage{fancyvrb}
\begin{document}
\begin{VerbatimOut}{\jobname-later.tex}
\begin{verbatim}
foo() {
}
\end{verbatim}
\end{VerbatimOut}
Something
\input{\jobname-later}
\end{document}
One can use the infrastructure of fancyvrb to define VerbatimOutAppend so that the file is closed only when we want to.
\documentclass{article}
\usepackage{fancyvrb}
\makeatletter
\newcommand{\OpenVerbatimOutAppend}[2]{%
\expandafter\newwrite\csname martin@write@#1\endcsname
\immediate\openout\csname martin@write@#1\endcsname=#2\relax
}
\newcommand{\CloseVerbatimOutAppend}[1]{%
\immediate\closeout\csname martin@write@#1\endcsname
}
\def\VerbatimOutAppend{\FV@Environment{}{VerbatimOutAppend}}
\def\FVB@VerbatimOutAppend#1{%
\@bsphack
\begingroup
\FV@UseKeyValues
\FV@DefineWhiteSpace
\def\FV@Space{\space}%
\FV@DefineTabOut
\expandafter\let\expandafter\FV@OutFile\csname martin@write@#1\endcsname
\def\FV@ProcessLine{\immediate\write\FV@OutFile}%
\let\FV@FontScanPrep\relax
\let\@noligs\relax
\FV@Scan}
\def\FVE@VerbatimOutAppend{\endgroup\@esphack}
\DefineVerbatimEnvironment{VerbatimOutAppend}{VerbatimOutAppend}{}
\makeatother
\begin{document}
\OpenVerbatimOutAppend{default}{\jobname-later.tex}
\begin{VerbatimOutAppend}{default}
\begin{verbatim}
foo() {
}
\end{verbatim}
\end{VerbatimOutAppend}
Something
\begin{VerbatimOutAppend}{default}
\begin{verbatim}
foo() {
}
\end{verbatim}
\end{VerbatimOutAppend}
\CloseVerbatimOutAppend{default}
\input{\jobname-later}
\end{document}
Several output files can be active at the same time; to each we assign a symbolic name, in the example it is default. Here's the content of the output file:
\begin{verbatim}
foo() {
}
\end{verbatim}
\begin{verbatim}
foo() {
}
\end{verbatim}
verbatimpackage has a\verbatimwritecommand. does this help? – barbara beeton Jul 01 '15 at 13:57