如果檔案遺失,如何防止 \input 失敗?

如果檔案遺失,如何防止 \input 失敗?

我在這裡讀到(對該問題的第二條評論)

我什麼時候應該使用 \input 和 \include?

\@input“如果檔案不存在,則不會拋出錯誤” 。

如果我嘗試

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

我確實沒有得到致命的錯誤,但我仍然收到 3 個編譯錯誤,更重要的是,我的 pdf 包含單字「inputtoBeIncluded.tex」。

有沒有一個簡單的方法完全忽略如果輸入檔不存在則輸入指令?

多謝

答案1

您需要新增才能在巨集中\makeatletter使用該符號。@

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

\end{document}

編輯

myfile.tex正如@Emil Jeřábek 所指出的,這會產生在讀取時更改@ 的catcode 的副作用。這不太可能產生任何不利影響,但可以透過以下方式避免:

\documentclass{article}

\makeatletter
\let\conditionalinput\@input
\makeatother

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

\InputIfFileExists{file}{}{}也就是說,按照 @daleif 的建議,使用 可能會更好。

答案2

而不是使用\@input更好的方法可能是使用

\InputIfFileExists{file}{then}{else}

如果存在的話就會運行\inputfile然後執行 中的程式碼then。如果檔案不存在,則else執行 中的程式碼。例如,您可以在該部分中新增警告else,只是為了通知您未找到該特定檔案。

如果您只想在檔案存在時閃爍輸入,只需使用

\InputIfFileExists{file}{}{}

有關此巨集的更多詳細信息,請參閱第 19 部分texdoc source2e中的描述ltfiles.dtx文件處理

相關內容