\openin & \openout (LaTeX2e unofficial reference manual (November 2018))

Next: \read, Up: Input/output [Contents][Index]

### 27.1 `\openin` & `\openout`

Synopsis:

    \openinnumber=filename

or:

    \openoutnumber=filename

Open a file for reading material, or for writing it. The number must be between 0 and 15, as in `\openin3` (in LuaLaTeX number can be between 0 and 255).

Here TeX opens the file `presidents.tex` for reading.

    \newread\presidentsfile
    \openin\presidentsfile=presidents
    \typeout{presidentsfile is \the\presidentsfile}
    \read\presidentsfile to\presidentline
    \typeout{\presidentline}

The `\newread` command allocates input stream numbers from 0 to 15 (there is also a `\newwrite`). The `\presidentsfile` is more memorable but under the hood it is still a number; the first `\typeout` gives something like ‘`presidentsfile is 1`’. In addition, `\newread` keeps track of the allocation so that if you use too many then you get an error like ‘`! No room for a new \read`’. The second `\typeout` gives the first line of the file, something like ‘`1 Washington, George`’.

Ordinarily TeX will not try to open the file until the next page shipout. To change this, use `\immediate\openinnumber=filename` or `\immediate\openoutnumber=filename`.

Close files with `\closeinnumber` and `\closeoutnumber`.

How LaTeX handles filenames varies among distributions, and even can vary among versions of a distribution. If the file does not have an extension then TeX will add a `.tex`. This creates `presidents.tex`, writes one line to it, and closes it.

    \newwrite\presidentsfile
    \openout\presidentsfile=presidents
    \write\presidentsfile{1 Washington, George}
    \closeout\presidentsfile

But filenames with a period can cause trouble: if TeX finds a filename of `presidents.dat` it could look first for `presidents.dat.tex` and later for `presidents.dat`, or it could do the opposite. Your distribution’s documentation should say more, and if you find something that works for you then you are good, but to ensure complete portability the best thing is to use file names containing only the twenty six ASCII letters (not case-sensitive) and the ten digits, along with underscore and dash, and in particular with no dot or space.

For `openin`, if TeX cannot find the file then it does not give an error. It just considers that the stream is not open (test for this with `\ifeof`; one recourse is the command `\InputIfFileExists`, see Class and package commands). If you try to use the same number twice, LaTeX won’t give you an error. If you try to use a bad number then you get an error message like ‘`! Bad number (16). <to be read again> = l.30 \openin16=test.jh`’.

Unofficial LaTeX2e reference manual