The simplest way to count the number of lines in a file seems to be to use the ε-TeX primitive \readline. (One could probably get away with using the TeX primitive \read instead, but that reads lines according to the current catcodes set. Also, the code is slightly more complicated since we cannot use \unless without ε-TeX.)

\newread\lf
\newcount\linecount
\newcommand\linesinfile[1]{%
        \linecount-1
        \openin\lf#1
        \unless\ifeof\lf
                \loop\unless\ifeof\lf
                        \readline\lf to\lfline
                        \advance\linecount by1
                \repeat
                \closein\lf
        \fi
}

If the file does not exist, \linecount will be -1. Otherwise, it'll contain the number of lines in the file.

Note: The copyright belongs to the blog author and the blog. For the license, please see the linked original source blog.