[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:



      {\CatchFileDef{\filecontent}{#1}{\endlinechar=`^^J\catcode\endlinechar=12\relax}}% keep existing end-of-lines
    \immediate\write\appendwrite{\filecontent #2}%


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


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



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