Write a \setcounter command to a file

I try to write a setcounter command to a file (using the newfile package) by something like the following

\addtostream{mystream}{\protect\setcounter{mycounter}{\myvariable}}


However, since the whole thing is protected, \myvariable isn't expanded and since it's value changes later in the document, the wrong value ends up in my counter. So, how can I 'unprotect' the variable here?

---EDIT--- Here's the minimal example:

\documentclass{article}

\usepackage{newfile}

\begin{document}
\newoutputstream{stream}
\openoutputfile{stream.file}{stream}

\newcounter{mycounter}
\setcounter{mycounter}{6}

\protect\setcounter{othercounter}{mycounter}%
}
\closeoutputstream{stream}

\end{document}


It outputs a file called stream.file with the content

\setcounter{othercounter}{mycounter}


but I want

\setcounter{othercounter}{6}

• Can you please add a minimal example from \documentclass to \end{document}? As far as I know, macros are expanded, which is the reason why \setcounter needs \protect. Mar 13 '13 at 19:03
• @egreg I added a minimal example. I hope it is more clear now. Mar 13 '13 at 22:52
• You have to say \themycounter or \arabic{mycounter} in the \addtostream command. Mar 13 '13 at 22:52

If othercounter and mycounter are LaTeX counters, you can't say

\setcounter{othercounter}{mycounter}


but, in general, you should say

\setcounter{othercounter}{\value{mycounter}}


However, for your application you need a different way, because you need the actual value of mycounter, not referring to the value at the time the assignment is performed. Thus

\addtostream{stream}{%
\protect\setcounter{othercounter}{\arabic{mycounter}}%
}


is what you're looking for. The write operation will expand \arabic{mycounter} to the current decimal representation of the counter's value.

\protect only protects the next token, not the arguments of the next token. If \myvariable is not expanded, then it is perhaps not expandable (e.g. defined by \newcount\myvariable. Then \number helps:

\addtostream{mystream}{%
\protect\setcounter{mycounter}{\number\myvariable}%
}%