# \unexpand\expandafter add spaces : how to append a text at the end of a file

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}

• The behaviour is by-design: you'll have to go for a token-by-token conversion to a string to avoid it – Joseph Wright Apr 11 at 17:42
• @JosephWright I have no idea how to do that (LaTeX is still a mystery for me), could you provide an example please? – tobiasBora Apr 11 at 17:55
• This happens because when TeX reads the file the \ is the control character thus \Mycode is a control sequence and TeX adds a space after that, as Joseph said, by-design. You can do \let\do\@makeother\dospecials before \CatchFileDef then the file would be read verbatim and \Mycode0 would be just a sequence of 8 characters. – Phelype Oleinik Apr 11 at 17:56

You can read the file back with a verbatim \

\documentclass{article}
\usepackage{verbatim}

\usepackage{catchfile}

\newwrite\appendwrite
\newcommand*\appendtofile[2]{%
\begingroup
\IfFileExists{#1}%
{\CatchFileDef{\filecontent}{#1}{\catcode\\=12 \endlinechar=^^J\catcode\endlinechar=12\relax}}% keep existing end-of-lines
{\let\filecontent\empty}%
\immediate\openout\appendwrite=#1\relax
\immediate\write\appendwrite{\detokenize\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}
`