Determine what line ending is used in a text file
I'd just search the file for the first \r
or \n
and if it was a \n
I'd look at the previous character to see if it's a \r
, if so, it's \r\n
otherwise it's whichever found.
Notice that text files may have inconsistent line endings. Your program should not choke on that. Using ReadLine
on a StreamReader
(and similar methods) will take care of any possible line ending automatically.
If you manually read lines from a file, make sure to accept any line endings, even if inconsistent. In practice, this is quite easy using the following algorithm:
- Scan ahead until you find either CR or LF.
- If you read CR, peek ahead at the next character;
- If the next character is LF, consume it (otherwise, put it back).
Here is some advanced guesswork: read the file, count CRs and LFs
if (CR > LF*2) then "Mac"
else if (LF > CR*2) then "Unix"
else "Windows"
Also note, that newer Macs (Mac OS X) use Unix line endings