You have to hide # from the text of \loop, since it does
\def\iterate{<text up to \repeat>}
A way can be as follows
\documentclass{article}
\edef\hashmark{\string#}
\def\getfirst#1#2\getfirst{\string#1}
\newread\myread
\begin{document}
\openin\myread=mysrcfile.txt
\newcount\linecount
\global\linecount1
\loop
\unless\ifeof\myread
\read\myread to \myinput
\if\hashmark\expandafter\getfirst\detokenize\expandafter{\myinput}\getfirst
\else
\expandafter\myinput
\fi
\global\advance\linecount1
\repeat
\closein\myread
\end{document}
The delimiter, instead of \relax is \getfirst which should not appear in the input file.
This requires e-TeX; without e-TeX you can change the category code of #:
\long\def\getfirst#1#2\getfirst{#1}
\openin\myread=mysrcfile.txt
\newcount\linecount
\global\linecount1
\begingroup\catcode`#=12
\loop
\unless\ifeof\myread
\read\myread to \myinput
\if\hashmark\expandafter\getfirst\myinput\getfirst
\else
\expandafter\myinput
\fi
\global\advance\linecount1
\repeat
\endgroup
\closein\myread
The \long is to protect against empty lines in the input file.
A possible implementation with LaTeX3 macros; it's always quite hard to deal with #:
\documentclass{article}
\usepackage{xparse,l3str}
\ExplSyntaxOn
% the user level command
\NewDocumentCommand{\readremovingcomments}{m}
{
\penguin_read_nocomments:n { #1 }
}
% the low level command
\cs_new_protected:Npn \penguin_read_nocomments:n #1
{
% open the input stream
\ior_open:Nn \l_penguin_source_ior { #1 }
% read one line at a time
\ior_map_inline:Nn \l_penguin_source_ior
{
% extract the first token from the input line (after stringifying it)
\tl_set:Nx \l__penguin_temp_tl { \tl_head:f { \tl_to_str:n { ##1 } } }
% check whether the first token is #; if not, print the line
\tl_if_eq:NNF \l__penguin_temp_tl \c_hash_str { ##1 }
}
\ior_close:N \l_penguin_source_ior
}
\tl_new:N \l__penguin_temp_tl
\ior_new:N \l_penguin_source_ior
\ExplSyntaxOff
\begin{document}
\readremovingcomments{mysrcfile.txt}
\end{document}
#is a parameter token, or is it acceptable to read with an alternative catcode? – Joseph Wright Dec 25 '12 at 11:28