0

Common programming languages (PL), e.g. Python allow append lines to opened file like file_object = open('sample.txt', 'a').

How it is possible to do in expl3 PL? My MWE adds only last argument of \somemacro. Please point to the right place in Interface3 how to do it.

\documentclass[]{article}

\ExplSyntaxOn \iow_new:N \l_totoc_iow

\NewDocumentCommand{\somemacro}{ m } { \iow_open:Nn \l_totoc_iow {\g_file_curr_name_str.dat} \iow_now:Nn \l_totoc_iow { #1 } \iow_close:N \l_totoc_iow } \ExplSyntaxOff

\begin{document}

\somemacro{tofile} \somemacro{tofile2}

\end{document}

sergiokapone
  • 5,578
  • 1
  • 16
  • 39
  • 1
    remember that (la)tex is not a common programming language. I'm actually not even sure if (la)tex supports appending to a file. Normally the file would be open for the entire compilation – daleif Jun 07 '22 at 10:39
  • 1
    The variable should be named like \l_pkgname_totoc_iow (note the suffix). – frougon Jun 07 '22 at 10:42
  • As soon as you open a file for writing, its previous content is destroyed. Just remove \iow_close:N \l_totoc_iow – egreg Jun 07 '22 at 10:53
  • That's the reason why LaTeX2e keeps open the .aux file and writes all other write instructions into it (and keeping many files open is unpracticable if you only can open a dozen or so) – Skillmon Jun 07 '22 at 11:00
  • There are ways to do this with lualatex though. – Niranjan Jun 07 '22 at 11:15
  • 1
    Remark: I know that there's no existing expl3 answer there; nevertheless • the principle is the same (read all, rewrite) and • if anyone wants to post an expl3 answer, please post the answer there. That way people who find that question can find your answer more easily. – user202729 Jun 07 '22 at 14:58

1 Answers1

4

The rule of TeX is that when a file is opened for writing in it, its previous content is destroyed. There's nothing to do about it.

Guessing from your naming of the file handle, you want to do something similar to producing a table of contents.

How is this solved by LaTeX? Instructions to write to the toc file are not directly written in it, because it cannot be known when it will be used for reading and printing from it. Rather, the instructions are written in the .aux file and a new version of the .toc file is written out at end document, when nothing more will be printed (LaTeX has already scanned \end{document}). Thus at each time during the LaTeX run, the previous version of the .toc file is available for reading.

Note that you cannot have a file opened for writing and read from it.

egreg
  • 1,121,712