[Tex/LaTex] How to automatically include all source code files located in a given directory

listings

Is there a way to include all files in a directory and all sub directories in a report as a code appendix using the listings package?

I know I can include each individual file using the listings package and \lstinputlisting, but I'm just wondering whether there is a quicker way to insert them in a code appendix…

Best Answer

A good solution that also works for listings was provided here: How to iterate through the name of files in a folder. You just have to modify the code like this:

\documentclass{article}
\usepackage{listings}

\makeatletter
\def\app@exe{\immediate\write18}
\def\listDir#1{%
  \app@exe{ls #1/* | xargs cat >> \jobname.tmp}%
  \lstinputlisting{\jobname.tmp}
  \AtEndDocument{\app@exe{rm -f #1/\jobname.tmp}}}
\makeatother

\begin{document}

\listDir{your_directory}

\end{document}

Note that, if you are running under windows, you will have to replace \app@exe commands by something like (not tested, but based on the answer given in the previous thread):

\app@exe{cmd /c dir /b * > \jobname.tmp}%
\AtEndOfDocument{\app@exe{rm -f #1/\jobname.tmp}}}

The code I gave will include all the files of the directory. If you want to only include files with a given extension you can specify it directly in \app@exe command.

Don't forget to compile using pdflatex -shell-escape yourfile.tex.