# Including all files within a directory [duplicate]

Possible Duplicate:
How to iterate through the name of files in a folder

Using \input{filename}, I can input a file canned "filename.tex". I have a directory containing all of the files I want to include. How can I create a for loop, which inputs all of those files?

• The contents of the directory sometimes changes (so I do not want to manually specify all of the files).
• The files are numbered (e.g. file01.tex, file02.tex), so the loop should have no difficulty inputing them in the correct order.
• Other code will be placed within the for loop (before and after the input command), so I do not want to simply list all of the files at once (e.g. \input{file01,file02}).
-

## marked as duplicate by Martin Scharrer♦Dec 17 '11 at 8:55

I closed this as a duplicate. The principle solutions are shown there and adding any extra code before or after is trivial. As shown there you either need to use an external script, LuaTeX or well named file names. If you think otherwise, please comment or edit your question and feel free to flag for reopening the question. –  Martin Scharrer Dec 17 '11 at 8:58
For a more advanced case see: tex.stackexchange.com/a/25261/9467 –  Oh my ghost Dec 17 '11 at 11:32

You can use a \foreach loop:

\documentclass{article}
\usepackage{pgffor}
\usepackage{filecontents}% Used so that the external files can be placed in this file

\begin{filecontents}{file01.tex}
\section{File 01}
\end{filecontents}

\begin{filecontents}{file02.tex}
\section{File 02}
\end{filecontents}

\begin{document}

\foreach \i in {00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, ...,19} {%
\edef\FileName{file\i}%     The % here are necessary to eliminate any
\IfFileExists{\FileName}{%  spurious spaces that may get inserted
\input{\FileName}%       at these points
}
}

\end{document}


Note that I added % to places where TeX would have inserted a spurious space. See for Tex Capacity Exceeded (if remove % after use of macro) as to the dangers of leaving those out.

-
Is there any way to define "19" (the number in the last file or value of the total number of files within the directory) automatically? –  Village Dec 17 '11 at 6:01
It is easier to to just use a number larger than the max number of expected files, say "99", or "999". The extra time required to check them all should be minimal. Getting the number of files in the directory is probably OS dependent. –  Peter Grill Dec 17 '11 at 18:17