# input filename as caption in listing

I'm working on the following piece of code

\newcommand{\mycin}[1]{% new command for icluding piece of code from external files
\lstinputlisting{#1}
}


I want to add a caption that reflects the name of the actual filename included by the command, i tryed something like

\newcommand{\mycin}[1]{% new command for icluding piece of code from external files
\lstinputlisting[caption=\caption{#1}]{#1}
}


or

\newcommand{\mycin}[1]{% new command for icluding piece of code from external files
\lstinputlisting[caption={#1}]{#1}
}


but both solutions do not works, there is a way to automate the generation of a caption in a newcommand?

-
It is always best to compose a MWE that illustrates the problem including the \documentclass and the appropriate packages so that those trying to help don't have to recreate it. –  Peter Grill Nov 10 '11 at 19:15
And always state what and how it "doesn't work", i.e. the error you get. –  Martin Scharrer Nov 10 '11 at 19:33

Your attempt would actually work for file names without special characters like _, ^, &, \$ etc. which have special meaning in (La)TeX.

You can turn them back to normal characters using \detokenize (which requires e-TeX, i.e. a LaTeX compiler which is less than a few years old, and not the Science Workplace version). (There is also a non-e-TeX way)

You need tt font to display these characters correctly:

\documentclass{article}
\usepackage{listings}
\newcommand{\mylisting}[2][]{%
\lstinputlisting[caption={\texttt{\detokenize{#2}}},#1]{#2}%
}

\begin{document}

\mylisting{foo.c}

\mylisting[frame=rlbt,language=C]{foo_bar.c}

\end{document}


-
Thanks, all seems to work very well –  Micro Nov 10 '11 at 19:35
\documentclass{article}
\usepackage{listings}

\lstset{
caption=\lstname
}
\begin{document}

\lstinputlisting{foo.c}

\lstinputlisting[frame=rlbt,language=C]{foo_bar.c}

\end{document}


Same output, but without Macros.

-
Welcome to TeX.SX. It is always better to add a minimal working example (MWE) starting with \documentclass{...} and ending with \end{document}. This makes the answer more clear. –  Claudio Fiandrino Apr 3 '13 at 12:42