Here is some code for Martin's comment:
\documentclass{article}
\usepackage{scrlfile}% KOMA-Script package with it's own documentation
\makeatletter
\newcommand*{\demomycounter}{% This is only for demonstration and not part of the suggestion
\@whilenum \value{page}<2\do {%
Usage of mycounter with value \stepcounter{mycounter}\themycounter.\par
}%
}
\newcommand*\storecounteratend[1]{% command to tell LaTeX to save the last value for the next run
\BeforeClosingMainAux{%
\immediate\write\@auxout{%
\string\restorecounteratbegin{#1}{\csname the#1\endcsname}%
}%
}%
}
\newcommand*{\restorecounteratbegin}[2]{% used at the aux file
\expandafter\gdef\csname stored@#1\endcsname{#2}%
}
\newcommand*{\storedcounter}[1]{% user command to ask for the value
\@ifundefined{stored@#1}{???}{\csname stored@#1\endcsname}%
}
\makeatother
\newcounter{mycounter}
\storecounteratend{mycounter}
\begin{document}
Last value of mycounter was \storedcounter{mycounter}.
\demomycounter
\end{document}
Instead of using \BeforeClosingMainAux from package scrlfile, you may use \AfterLastShipout with package atveryend.
Another solution would be to use \refstepcounter instead of \stepcounter. In this case, you simply have to write a label at the end of the document and may use \ref:
\documentclass{article}
\usepackage{scrlfile}
\newcounter{mycounter}
\BeforeClosingMainAux{\label{mycounter}}
\makeatletter
\newcommand*{\demomycounter}{% This is only for demonstration and not part of the suggestion
\@whilenum \value{page}<2\do {%
Usage of mycounter with value \refstepcounter{mycounter}\themycounter.\par
}%
}
\begin{document}
Last value of mycounter was \ref{mycounter}.
\demomycounter
\end{document}
If you need not a reference to the counter but the value, you may combine the second suggestion with package refcount.
.auxfile, then you can read it back at the beginning. I'm sure someone will post some code for that soon. – Martin Scharrer♦ Nov 14 '11 at 12:12totcountpackage. Would it have been better if I had started a new, identical question, but specific to ConTeXt, rather than add a bounty? – Village May 10 '12 at 8:46