1

I am a TeX user, and I would like to read a number from an auxiliary file in order to achieve things like: printing at the footing "page number X out of Total". I was trying to use the primitives commands \openin and \read, but \read only reads text into macros (according to the TeXbook page 217) and I don't see how I could read a number from a file into a count register.

Any hints? Thanks in advance.

1 Answer 1

2

Read the file as written in the previous run.

\input plipsum % for mock text

% save the total page number in a file (hook into \bye)
\outer\def\bye{\par\vfill\supereject\writetotal\end}
\def\writetotal{%
  \immediate\openout\totalfile=\jobname.tot
  \immediate\write\totalfile{\the\pageno}%
  \immediate\closeout\totalfile
}
\newwrite\totalfile
\newread\totalread

% at the start we read the file
\openin\totalread=\jobname.tot
\ifeof\totalread
  % the file doesn't exist
  \def\totalpage{0}%
\else
  % define \totalpage to the contents of the first line in the tot file
  \read\totalread to \totalpage
  % it will have a space at the end
\fi
\closein\totalread

\footline{\hfil Page number \folio\ out of total \totalpage\unskip\hfil}

\lipsum{1-40}

\bye

If you insist to have a count register, just set it:

\input plipsum

\outer\def\bye{\par\vfill\supereject\writetotal\end}
\def\writetotal{%
  \immediate\openout\totalfile=\jobname.tot
  \immediate\write\totalfile{\the\pageno}%
  \immediate\closeout\totalfile
}
\newwrite\totalfile
\newread\totalread
\newcount\totpages

\openin\totalread=\jobname.tot
\ifeof\totalread
  \def\totalpage{0}%
\else
  \read\totalread to \totalpage
\fi
\totpages=\totalpage
\closein\totalread

\footline{\hfil Page number \folio\ out of total \number\totpages\hfil}

\lipsum{1-40}

\bye
3
  • Thanks, this does the trick for the task of the "total number of pages", but still \totalpage is not a count register it's only a string of characters. Is it possible to get an integer from a string of characters in TeX, just like atoi() in C?
    – Lagrang3
    May 7, 2018 at 20:57
  • @Lagrange.el.Ciencia What's the purpose of such a count register? Anyway, it's easy to add it.
    – egreg
    May 7, 2018 at 20:58
  • @Lagrange.el.Ciencia You need to go through a macro, because that's the only way to read lines from a file (unless e-TeX is allowed).
    – egreg
    May 7, 2018 at 21:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .