[Tex/LaTex] At which point does \immediate\write write to file

expansionexternal fileswrite

Assume I have opened a file myfile and write to it with

 \immediate\write\myfile{My cat is too old}

I have multiple such statements in my document and do calculations in between which influence the outcome of the writing. Up to now, I do not completely understand, when the actual writing is done, especially if the above code is part of the definition of a command.

Can somebody shade light on that issue?

Best Answer

Storing a command in a macro does not execute it, so

\newcommand{\demo}[1]{\immediate\write\myfile{#1}}

does nothing until you use \demo:

\demo{My cat is too old}

expands to

\immediate\write\myfile{My cat is too old}

which TeX then starts to execute (as \immediate and \write are non-expandable primitives, not macros). Writing to the file takes place at this point: as soon as TeX reaches the end of the second argument (... old}) it will write to the file.

The \immediate here is used as the alternative

\write\myfile{My cat is too old}

does not write to the file 'now'. Instead, it stores the information, and writes to the file when the next page is shipped out. This is required to get, for example, page numbers correct in the argument, but would give the wrong result if you tried to read back the file before the next shipout.