我想将代码附加到包含乳胶代码的文件中...所以我尝试了这里提出的解决方案,但不幸的是,当文件中有反斜杠时它会失败:如何以“追加”模式打开文件?
所以我尝试用它来调整它\unexpand\expandafter{\filecontent}#2
,但是它在“命令”后面添加了空格,这真的很烦人:
梅威瑟:
\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}
答案1
你可以逐字逐句地读回文件\
\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}