Read number lines in a file - in LaTeX

Posted by ads' corner on Sunday, 2010-02-28
Posted in [Tex]

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
\documentclass{book}

\usepackage{ifthen}

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

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

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

\newcommand{\ReadNextLine}[1]{
 \ifthenelse{\boolean{RestFile}}{
 \read#1 to \FileLine
 \ifeof#1\setboolean{RestFile}{false}
 \else % if last line already is read, EOF appears here
 \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.


Categories: [Tex]