[Tex/LaTex] how to prevent \input from failing if the file is missing

input

I read here (second comment to the question)

When should I use \input vs. \include?

that \@input "does not throw an error if the file does not exist".

If I try

\documentclass{article}
\begin{document}
\@input{toBeIncluded.tex}
\end{document}

I indeed get no fatal error, but still i get 3 compilation errors and, more importanly, my pdf contains the word "inputtoBeIncluded.tex".

Is there a simple way to completely ignore the input command if the input file does not exist?

Thanks a lot

Best Answer

You need to add \makeatletter to enable the use of the symbol @ in a macro.

\documentclass{article}
\begin{document}
abc
\makeatletter
\@input{myfile.tex}
\makeatother   

\end{document}

EDIT

As noted by @Emil Jeřábek, this has the side effect of changing the catcode of @ whilst myfile.tex is being read. This is unlikely to have any adverse effects, but it could be avoided as follows:

\documentclass{article}

\makeatletter
\let\conditionalinput\@input
\makeatother

\begin{document}
abc
\conditionalinput{fred.tex}
\end{document}

That said, it's probably better to use \InputIfFileExists{file}{}{}, as suggested by @daleif.

Related Question