I'd like to append code to a file containing latex code... So I tried the solution proposed here, but unfortunately it fails when there are backslash in the file: How can I open a file in "append" mode?
So I tried to adapt it with \unexpand\expandafter{\filecontent}#2, but it adds spaces after "commands", which is really annoying:
MWE:
\documentclass{article}
\usepackage{verbatim}
\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{\unexpanded\expandafter{\filecontent}#2}%
\immediate\closeout\appendwrite
\endgroup
}
\newcounter{mycounter}
\begin{document}
\appendtofile{\jobname.test}{\string\Mycode\themycounter}
First, everything is good:\\
\verbatiminput{\jobname.test}
\appendtofile{\jobname.test}{Second line}
Second, see how the spaces are added:\\
\verbatiminput{\jobname.test}
\end{document}


\is the control character thus\Mycodeis a control sequence and TeX adds a space after that, as Joseph said, by-design. You can do\let\do\@makeother\dospecialsbefore\CatchFileDefthen the file would be read verbatim and\Mycode0would be just a sequence of 8 characters. – Phelype Oleinik Apr 11 '19 at 17:56