read and write commands to auxfile

When LaTeX reads the .aux file, then it reads it inside a local group. \newcount assigns the count register globally, but the assignment \counti=... is local like LaTeX's \setlength but unlike LaTeX's \setcounter. Therefore the problem can be fixed by a global assignment:

\write\@auxout{\global\counti= \the\counti\relax}

(I have added \relax. Then TeX will not parse beyond to find digits.)


Here is a more "latexy" way of doing this using Heiko's refcount package. The idea is to save the value of the counter to the auxfile, as a label, and then read it back in each time the file is compiled using \setcounterref.

The output of the MWE below takes the form:

enter image description here

where the value of the counter increments each time.

\documentclass{article}
\usepackage{refcount}\setrefcountdefault{0}
\usepackage{etoolbox}

\newcounter{TestCounter}

\AtEndDocument{% save counter value to aux file at end of document
  \addtocounter{TestCounter}{-1}%
  \refstepcounter{TestCounter}\label{Ref:TestCounter}% 
}
\AfterEndPreamble{% set counter using value saved in aux file
 \setcounterref{TestCounter}{Ref:TestCounter}%
}

\begin{document}

Counter is \arabic{TestCounter}

\addtocounter{TestCounter}{1}

\end{document}

I have automated this using \AtEndDocument and \AfterEndPreamble commands from the etoolbox package. (This is just for proof-of-concept. There are better ways of writing to the auxfile that avoid decrementing and then incrementing the counter.)