Keith Thompson wrote:
>
> If you've opened the file in text mode, the end-of-line will appear in
> the string as a single '\n' character, regardless of how it's
> represented in the external file.
> [...]
Let's add a caveat, disclaimer, and weasel-word to that
nice-sounding guarantee: It's only true if the text file is
"well-formed" according to the system's conventions. If you
somehow get hold of a "foreign" file that hasn't been properly
translated to the local dialect, all bets are off.
The O.P. doesn't actually say that he needs to read "\r\n"-
terminated lines on an "\n"-only system, but there seems to be
a whiff of that possibility in the air. Maybe he's reading a
text file that was FTP'ed in binary mode, or a foreign-format
file residing on a shared disk, or ... He writes of the "\r\n"
in a way that makes me think he's actually found them in his
buffers. (Maybe he hasn't, but it sounds that way.)
> If you've read a complete line with fgets(), it's easy enough to get
> rid of the trailing '\n': just replace it with a '\0'. [...]
Right. And if the trailing '\n' is immediately preceded by
an '\r' he could obliterate that, too, trying to patch things up
for a file that was transferred from a DOS-ish environment to a
different one without proper translation. Ultimately, though,
that's a losing proposition: There are just too many different
line-ending conventions kicking around, and trying to burden your
program with understanding all of them (especially after they've
been garbled by unsuccessful translation) is attacking the wrong
end of the problem. If the O.P. faces trouble of this kind, it's
better to fix the file transfer procedures than to try to repair
the damage afterwards -- get the transfer/translation done right,
and you're back in the nice state of affairs Keith describes.
--
Eric Sosman
lid