I am trying to write to a auxillary file using



\immediate\write\tempfile{Text to write to file}

It works like a charm for plain text but I need it to work with


How do I write it to the file without expansion and thus allowing me to insert the entire file in the end (in my answer section) of my document.


4 Answers 4


The simplest way to do this is to use \unexpanded which requires e-TeX (i.e.\ a not too old version of TeX):

\immediate\write\tempfile{\unexpanded{Text to write to file}}
  • 1
    @Mats: In this case use \noexpand on \input: \immediate\write\tempfile{\noexpand\input{ans\thesection-\arabic{enumi}} Aug 1, 2011 at 14:08

Either put \noexpand before a command which should not be expanded or \unexpanded{...} around a longer text.


What you want is etex's \unexpanded macro. Although, if you're using it with \thesection, are you sure this is actually what you want? For example, look at the following:


\immediate\write\tempfile{\unexpanded{Section \thesection}}


What this does is write \thesection to the temporary file and then input it back in later. As you'll see if you run it, it outputs "Something: Section 2"

Is this really the behaviour you want? If you are writing "answers" then presumably, you want it to refer back to the right section where the corresponding question was, in which case you will want it to expand \thesection at the time of writing.

There may still be stuff you want unexpanded, but think about what you want expanding and what you don't...

There's a lot more information about writing to files in this question: What is the basic mechanism for writing something to an aux file?


It sounds like you might be interested in using the answers package, below is a MWE.

It does all of the heavy lifting for you, and allows you to put anything you like in the solution files without having to escape any characters. It has a nice toggle feature that allows you to preview the answers next to the questions (see my MWE).

\usepackage{answers}                            % solutions to problems done *beautifully*
%\usepackage[nosolutionfiles]{answers}        % use this line if you want to see the answers 
                                                                                        % in the document

\newenvironment{problem}{\refstepcounter{problem} {\bfseries\theproblem}.\ }{}
% solution files


Here's a question
      Here's the answer- can put anything in here: e.g $\frac{1}{3}$

Here's another question
      Here's another answer- can put figures, tables- anything you like!

% close the solutions files

% input the SHORT solutions file


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.