You can write to the aux file with
Depending on requirements.
\immediate\write writes to the specified file at that point, expanding the supplied tokens (like
\edef) so fragile commands will do the wrong thing.
\write does not write at that point it puts a write node into the current vertical or horizontal list and if that list is shipped out to make a page then the write happens. This is needed to get page numbers correct. (If the write is inside a box and that box is never used on the main page then nothing is written to the file.)
\protected@write is a LaTeX-defined macro that uses
\write but arranges that
\protect works as required in LaTeX to protect fragile commands. The extra argument unused above allows you to locally insert extra definitions to make more commands be safe or have special definition in the write, see for example the definition of
It is safe to write to the aux file, however you have to be aware that the file will be read back at least at the begin and end of the document, so you need to write lines that are safe in that context.
If you want to write to your own file then you just need to do
in the preamble and then replace
\myfile when writing.
Have a look at the way
\listoffigures work in
latex.ltx or documented in source2e. They basically all use
\immediate\openout \csname tf@#1\endcsname \jobname.#1\relax