我是一名 TeX 用户,我想从辅助文件中读取一个数字,以便实现以下功能:在页脚处打印“页码 X,总页数”。我尝试使用原始命令 \openin 和 \read,但 \read 只能将文本读入宏(根据 TeXbook 第 217 页),我不知道如何将文件中的数字读入计数寄存器。
有什么提示吗?提前致谢。
答案1
读取上次运行中所写入的文件。
\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
如果你坚持要有一个计数寄存器,只需设置它:
\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