9

I don't want to get into the details of why I want to do this, but I would like to:

  • create a new counter called filenumber;
  • create a file whose filename is \jobname\thefilenumber.txt and write to it;
  • read (input) the content from that file.

Here's my mwe:

\documentclass[11pt]{article}

\usepackage{newfile}

\newcounter{filenumber}
\newoutputstream{outputfile}

\newcommand{\createoutputfile}[2]{%
  \refstepcounter{filenumber}\label{#1}

  \openoutputfile{\jobname\thefilenumber.txt}{outputfile}
  \addtostream{outputfile}{#2}
  \closeoutputstream{outputfile}
}


\begin{document}

\createoutputfile{timmyfile}{Hello world!}

Timmy, what would you like to tell the world?

Timmy's answer has been written to:\\
{\ttfamily \jobname\ref{timmyfile}.txt}

Timmy's answer: \input{\jobname1.txt}

%% The following does not work
\makeatletter
%{\@@input \jobname\ref{timmyfile}.txt}
\makeatother

\end{document}

I know that \input isn't expandable, but even using TeX's \@@input, I can't manage to input the file if I try to construct the filename using the label created earlier. Uncommenting the \@@input line actually has the perverse effect of creating 50 identical files (numbered from 1 to 50) containing "Hello world!".

If I use \include instead of \input to trace what is happening, the .aux file contains the following:

\relax 
\newlabel{timmyfile}{{1}{1}}
\@input{stackexchange_read_filename_from_ref1\hbox {}.txt.aux}

It seems that the reference is being expanded to 1\hbox {}.

Could this be the issue? How can I fix this and input a file whose filename is created using a label in such a way?

1 Answer 1

7

You want an expandable version of \ref:

\documentclass[11pt]{article}
\usepackage{refcount}
\usepackage{newfile}

\newcounter{filenumber}
\newoutputstream{outputfile}

\newcommand{\createoutputfile}[2]{%
  \refstepcounter{filenumber}%
  \label{THISFILE#1}%
  \openoutputfile{\jobname\thefilenumber.txt}{outputfile}
  \addtostream{outputfile}{#2}
  \closeoutputstream{outputfile}
}
\newcommand{\readfile}[1]{%
  \InputIfFileExists{\jobname\getrefnumber{THISFILE#1}.txt}{}{``RERUN''}%
}

\begin{document}

\createoutputfile{timmyfile}{Hello world!}

Timmy, what would you like to tell the world?

Timmy's answer: \readfile{timmyfile}

\end{document}

When the cross-reference is not solved, so the file is not found, ”RERUN” is printed.

1
  • There is an extra } in your code at line \openoutputfile{\jobname\thefilenumber}.txt}{outputfile} I believe you are a cyborg. ;) Nov 14, 2013 at 1:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .