Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 5 down vote accepted

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

share|improve this answer

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}
share|improve this answer
    
Well done. I was looking for a solution using custom list, in vain. –  Clément Jul 3 at 13:33
1  
PGF has already a temporary openin \r@pgf@reada for scratching stuff in case needed. –  percusse Jul 3 at 13:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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