[Tex/LaTex] How to open a file in “append” mode

auxiliary-filesexternal filesfilesystem-accesstex-core

Could not find anything in the TeXBook, but this could be just me.

I guess it is always possible to open
the file for reading, copy its content to another file, and then continue writing to that file. Finally, you could escape to shell to remove the original file and rename the newly generated file to the file you have just created.

Best Answer

I agree with Joseph that TeX doesn't support appending to an existing file. However it is possible to read the existing content and write it together with the new content back to the file. This is of course much less efficient than simply appending content, but the only possible way in TeX.

The catchfile makes the reading of the existing content quite easy:

\documentclass{article}

\usepackage{catchfile}

\newwrite\appendwrite
\newcommand*\appendtofile[2]{%
    \begingroup
    \IfFileExists{#1}%
      {\CatchFileDef{\filecontent}{#1}{\endlinechar=`^^J\catcode\endlinechar=12\relax}}% keep existing end-of-lines
      {\let\filecontent\empty}%
    \immediate\openout\appendwrite=#1\relax
    \immediate\write\appendwrite{\filecontent #2}%
    \immediate\closeout\appendwrite
    \endgroup
}

\begin{document}

\appendtofile{\jobname.test}{First line}

First:\\\fbox{\input{\jobname.test}}

\appendtofile{\jobname.test}{Second line}

Second:\\\fbox{\input{\jobname.test}}

\end{document}

See also the answers to the question "File copy without expansion".