Read a file and store its contents in a variable
I'm not sure what the right way to do this with the LaTeX macros like \IfFileExists
, but using the low-level TeX primitives this is easy to do.
\documentclass{article}
\newread\makerfile
\begin{document}
\openin\makerfile=../DecMaker.txt
\ifeof\makerfile
Go and buy a computer from ThisRandomBrand!!
\else
\read\makerfile to\makerline
\closein\makerfile
\edef\product{%
\ifcase\makerline
Windows%
\or Linux%
\or Mac%
\fi
}
\product\ computer bought from ThisRandomBrand is amazing!
\fi
\end{document}
It tries to open ../DecMaker.txt
and if that fails, it outputs the "Go and buy..." line. Otherwise, it defines \product
to Windows
, Linux
, or Mac
and outputs the "Linux computer..." line (for example).
I don't know (and cannot easily test) what happens if this file is actually run on a Windows machine. In particular, I don't know if ../DecMaker.txt
is treated as the path you want.
If DecMaker.txt
were moved to the same directory, then this should work correctly everywhere.
Run with lualatex
\documentclass{article}
\usepackage{luacode}
\begin{luacode}
local x = {"Windows","Linux","Darwin"}
function FileTest(filename)
local f=assert(io.open(filename, "r"))
local t=f:read()
f:close()
if t then
return x[tonumber(t)].." computer bought from ThisRandomBrand is amazing!"
else
return "Go and buy a computer from ThisRandomBrand!!"
end
end
\end{luacode}
\newcommand\Test[1]{\directlua{tex.print(FileTest("#1"))}}
\begin{document}
\Test{../DecMaker.txt}
\end{document}
You can use catchfile
. It's also better to separate the reading of the auxiliary file from the definition part, so you can easily reuse the code for the OS. The macro \newOScommand
has five arguments: the name of the command to define and the four branches as shown in the example.
\usepackage{catchfile}
\IfFileExists{../DecMaker.txt}
{\CatchFileEdef{\OSnumber}{../DecMaker.txt}{\endlinechar=-1 }}
{\def\OSnumber{-1}}
\newcommand{\newOScommand}[5]{%
\ifcase\OSnumber\relax
\newcommand{#1}{#2}\or
\newcommand{#1}{#3}\or
\newcommand{#1}{#4}\else
\newcommand{#1}{#5}%
\fi
\newOScommand{\product}{Windows}{Linux}{Mac}{No computer}