You can write to the aux file with
\write\@auxout{\gdef\string\testa{hello}}
or
\immediate\write\@auxout{\gdef\string\testb{hello2}}
or
\protected@write\@auxout{}{\gdef\string\testc{hello3}}
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 \index or \addtocontents.
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
\newwrite\myfile
\immediate\openout\myfile=\jobname.foo
in the preamble and then replace \@auxout by \myfile when writing.
Have a look at the way \tableofcontents or \listoftables or \listoffigures work in latex.ltx or documented in source2e. They basically all use
\def\@starttoc#1{%
\begingroup
\makeatletter
\@input{\jobname.#1}%
\if@filesw
\expandafter\newwrite\csname tf@#1\endcsname
\immediate\openout \csname tf@#1\endcsname \jobname.#1\relax
\fi
\@nobreakfalse
\endgroup}
auxfile:\immediate\write\@auxout{<something expandable>}or\write\@auxout{<something expandable>}. Theauxfile is automatically read in at begin document. – cgnieder May 24 '13 at 11:58VerbatimOutas provided byfancyvrb. there's a nice discussion in the companion of how it was used for the side-by-side examples in the book. – barbara beeton May 24 '13 at 13:02auxfile, usually they don't check for other files that were created and cause an error in the next run-through (which is imho a plus for writing to theauxfile and not create more files ...) – Jonathan Aug 21 '13 at 18:59