9

I want to create a loop including n images.The number n is the only content of a help file (created by the application that generates the images).
Is it possible to read the contents of the help file and use that as a number variable to set the loop?

The following code works:

\def\cnt{\input{numberfile}}
\cnt

Output is the number (i.e. the content of the file).

The following code doesn't work:

\newcounter{cnt}
\setcounter{cnt}{\input{numberfile}}
\arabic{cnt}

The error indicates that the input isn't a number ("Missing number, treated as zero").

So how can I convert the input file to a LaTeX number?

uli_1973
  • 1,920

2 Answers2

14

One way is to use \read which reads a file a line at a time

\documentclass{article}


\newcounter{cnt}
\newread\myread 
\openin\myread=numberfile



\begin{document}

\read \myread to \zz

\setcounter{cnt}{\zz}
\arabic{cnt}

\end{document}

assuming numberfile.tex looks like

33
David Carlisle
  • 757,742
11

Without a \read:

\documentclass{article}
\usepackage{catchfile}

\newcommand{\setcounterfromfile}[2]{% #1 = counter, #2 = file name
  \CatchFileDef{\scfftemp}{#2}{\endlinechar=-1 }%
  \setcounter{#1}{\scfftemp}}

\newcounter{cnt}

\setcounterfromfile{cnt}{numberfile}

\showthe\value{cnt}

If numberfile.tex contains the only line 12345 (a very difficult number to guess, as it's well known1) we get

> 12345.

1 The reference is, of course, to Mel Brooks' Space Balls.

egreg
  • 1,121,712
  • Correction to my comment on the other solution: My real task expects the file name to be passed as an argument, and the file name may contain special characters and does contain an additional dot. The \read solution doesn't work with that but the 'catchfile' approach does handle such filename without problems. – uli_1973 Feb 10 '13 at 13:20