3

Till now I guessed that \lstinputlisting{file.ext} just reads the contents of a file and uses it in a lstlisting environment. The sample file below compiles fine, but if I replace the content of the macro with the (my idea was: equivalent) other form, the compilation fails,

\documentclass{memoir}
\usepackage{listings}

\newcommand\MESFN[4][]{
   \lstinputlisting{a.c}
%  \begin{lstlisting}    int i, sum = 0;  \end{lstlisting}
}

\begin{document}
  \MESFN[]{}{}{}
\end{document}

I found the question (and reply) Why can lstlisting not be saved in a command?, and I understand why it fails. But, why the other form suceeds? Are there additional differences between providing a file or an immediate content for listings? (and maybe \lstinline also)

1

The simple reason is, that LaTeX only read the file name and not the contents of the file. In your example the file name is benign. But there are legal file names, which LaTeX will not work with (like the example below in \TEST).

If you want to have the source in your .tex file, you can use the package filecontents, which will generate the file you want to use in your macro.

\documentclass{memoir}
\usepackage{listings}
\usepackage{filecontents}

\begin{filecontents*}{b.c}
int i, sum = 0;

// crasy stuff, that LaTeX wouldn't like
c_r = a % b;
\end{filecontents*}

\newcommand\MESFN[4][]{
   \lstinputlisting{b.c}
}

\newcommand\TEST{
%   \lstinputlisting{b%29.c}
}

\begin{document}
  \MESFN[]{}{}{}
\end{document} 
  • The task is slightly misunderstood. I know and use filecontents, but in this case I have external files. The content of which appears in a verbatim environment. – katang Apr 3 '17 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.