## Read number lines in a file - in LaTeX

Probably a rare needed feature, but i had to count the number lines in a text file - in LaTeX.

Counting the line numbers is done by using a counter (what else, eh?) and readling the file line by line:

\documentclass{book}

\usepackage{ifthen}

\newcounter{FileLines}
\newboolean{RestFile}
\newcommand{\FileLine}{}

\newcommand{\CountLinesInFile}[2]
{
\setboolean{RestFile}{true}
\setcounter{FileLines}{0}

\openin\File=#1
\whiledo{\boolean{RestFile}}
{
\ifthenelse{\boolean{RestFile}}{
\stepcounter{FileLines}
}{}
}
\closein\File
}

\ifthenelse{\boolean{RestFile}}{
\ifeof#1\setboolean{RestFile}{false
}
\fi
}{}
}

\begin{document}

\CountLinesInFile{textfile.txt}

Lines in file: \arabic{FileLines}

\end{document
}

\File is a TeX file descriptor. Note that TeX has a very limited number of this file descriptors, but fortunately they can be re-used, as long as the descriptor is not used in parallel by different commands for a different operation.

The number of file lines is available in the \FileLines counter, which can be exported in arabic numerals by using \arabic{}.

More possible counter representations are explained in my previous post.