# Why does the following code run in an infinite loop?

\def\hcAuxText{}
\immediate\openin\hcInputStream=myfile.tmp
\loop\unless\ifeof\hcInputStream
\let\hcAuxAcumm\hcAuxText
\edef\hcAuxText{\hcAuxAcumm \hcAuxLine}
\repeat
\closein\hcInputStream


I am trying to read the contents of a file to a variable. I need the whole file to be read because the file will be later modified (like a table of contents).

When the above code is run, I get the following message:

! TeX capacity exceeded, sorry [input stack size=5000].
\@ifundefined #1->\expandafter \ifx \csname #1
\endcsname \relax \expandafter..


I would like to know i) why that code overflows the stack, and ii) is there a better way to read a whole file to a variable?

%%%%%%%%%% Edit %%%%%%%%%%

The ulterior motives for this code are to load a file into a variable which can then be "pasted" whenever used. The file is read \AtBeginDocument but it is modified when the source is processed. So, I want to keep the "initial state" of the file in memory. That might help with my question (ii) above.

As for part (i), I am baffled that the code above did not work. After all, I read a line storing it in \hcAuxLine, copy the previous state of \hcAuxAcumm to \hcAuxText, and finally concatenate {\hcAuxAcumm \hcAuxLine} to \hcAuxText.

-
Is that all of the code you have? Your error indicates that you are using LaTeX but the snippet is pure plain TeX. – Joseph Wright Dec 12 '10 at 17:04
Unfortunately, I do not know enough of either TeX or LaTeX to decide for the best tool, so I mix and match. The output of this routine is to be used as \hcAuxText and it should give the same result as \input{myfile.tmp}, except that myfile.tmp was written in between. – Hector Dec 12 '10 at 17:06

Taking it that the topic here is LaTeX, I'd look at the catchfile package. As to the message you get, it's a bit hard to be sure without some more context. I do wonder about using \edef here, though. It will fully expand the line that has just been read from the file, which may be a bad idea. This is a general point, and I'd at the very least consider using \protected@edef. If you don't want expansion, I'd suggest you're better avoiding it entirely. As you are using e-TeX, you'd be better with

\edef\hcAuxText{\unexpand\expandafter{\hcAuxText}\unexpand\expandafter{\hcAuxLine}}


By the way, there is no need to make a copy of \hcAuxText for the \edef step. A line such as

\edef\hcAuxText{\hcAuxText <extra stuff}


will expand \hcAuxText within the definition before the assignment.

-
catchfile did the trick, thank you! For the record, catchfile's content must have a "complete" command. If catchfile contained something like "\item a" then it fails. It must have something like "\begin{itemize}\item a\end{itemize}". ... As for the difference between \def and \edef, I thought they were like Mathematica's Rule and RuleDelayed, but it seems like there is more to it. – Hector Dec 12 '10 at 17:39