7

I want to read the upper bound for my foreach loop from a file. I've tried the following, but it gives all manner of errors.

\documentclass{article}
\usepackage{tikz}

\begin{filecontents*}{foo}
42
\end{filecontents*}

\begin{document}
\foreach\x in {1,...,\input{foo}} {\x,}
\end{document}

I've also tried saving the \input{foo} into a command, and then putting that command name in as the foreach's upper bound. But that doesn't seem to help.

5

You can use catchfile:

\documentclass{article}
\usepackage{tikz,catchfile}

\begin{filecontents*}{\jobname.dat}
42
\end{filecontents*}

\begin{document}

\CatchFileDef\upperlimit{\jobname.dat}{}
\foreach\x in {1,...,\upperlimit} {\x, }
\end{document}

(I used a different name for the file in order not to clobber any of my files.)

enter image description here

5

If you are willing to change the contents of foo to latex code:

\documentclass{article}
\usepackage{tikz}

\begin{filecontents*}{foo}
\def\limit{42}
\end{filecontents*}


\begin{document}
\input{foo}
\foreach\x in {1,...,\limit} {\x,}
\end{document}

If you just want "42" you can use:

\documentclass{article}
\usepackage{tikz}

\begin{filecontents*}{foo}
42
\end{filecontents*}

\begin{document}
\newread\io%
\openin\io=foo%
\read\io to\limit%
\closein\io%

\foreach\x in {1,...,\limit} {\x,}
\end{document}
  • Well done. I was looking for a solution using custom list, in vain. – Clément Jul 3 '14 at 13:33
  • 1
    PGF has already a temporary openin \r@pgf@reada for scratching stuff in case needed. – percusse Jul 3 '14 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.