7

I want to create a new temporary file (named main-temp.tex), append data to it multiple times, and import the contents later. I haven't learnt how to use TeX file operation, both reading and writing.

In this question, I think I need writing operation only because reading data from a file line by line is not needed in my scenario below. Thus using \input{} is enough to read all data.

% main.tex

\documentclass{article}
\usepackage{xcolor}

\newcommand\AppendAnswer[1]
{
    % code to append #1 to a shared temporary file named main-temp.tex
}

\newcommand\AddQuestion[2]% #1 and #2 stand for question and answer, respectively
{%
  % code to markup  question #1
  % for example
  {\color{blue}#1} 
  %
  % code to append answer #2
  \AppendAnswer{#2} 
}




\begin{document}
\section{Questions}
% Add some questions:
\AddQuestion{Are you kidding?}{No. I am not a joker.}
\AddQuestion{Really?}{Yes!}


\section{Answers}
% imports answers from the shared temporary file named main-temp.tex
\input{main-temp}

\end{document}

How to append data to a temporary file? I know using --enable-write18 switch is mandatory when invoking latex. I don't want to use the existing package such as exercise, etc.

Display Name
  • 46,933

1 Answers1

13

The basic code is as follows.

\documentclass{article}
\newwrite\ans
\immediate\openout\ans=\jobname-temp

\newcommand{\AddQuestion}[2]{#1\AppendAnswer{#2}}
\newcommand{\AppendAnswer}[1]{\immediate\write\ans{#1^^J}}
\newcommand{\PrintAnswers}{\immediate\closeout\ans\input{\jobname-temp}}

\begin{document}
\section{Questions}

\AddQuestion{Are you kidding?}{No. I'm not a joker.}
\AddQuestion{Really?}{Yes!}

\section{Answers}
\PrintAnswers
\end{document}

You are responsible for adding formatting directives to the answers file. You might profit from the \unexpanded feature, to avoid expanding commands during the \write operation:

\newcommand{\AppendAnswer}[1]{\immediate\write\ans{\unexpanded{#1}^^J}}

is a good way, but probably you'll need a mix of expanded and unexpanded writes: the reference number, for example, would need to be expanded. So, say you have a counter that keeps track of the questions

\newcounter{question}[section]
\renewcommand{\thequestion}{\thesection.\arabic{question}}

\newcommand{\AppendAnswer}[1]{%
  \immediate\write\ans{\thequestion}%
  \immediate\write\ans{\unexpanded{#1}^^J}}

after having defined \AddQuestion to also increment the question counter.

The final ^^J means that each answer will be followed by an empty line.

egreg
  • 1,121,712