views:

32

answers:

2

I'm reading text files but I don't know in advance the kind of line ending used in this file. I need to know whether it uses UNIX \n or windows style \r\n line endings.

What is a reliable and fast way to detect this?

+1  A: 

From wikipedia:

The file command also detects the type of EOL used:

file myfile.txt
> > myfile.txt: ASCII text, with CRLF line terminators

Source: http://en.wikipedia.org/wiki/Newline#Common_problems

Of course, file would only work on Unix systems. I'm sure someone else will answer one for Windows.

Xavier Ho
Basically, what I am interested in is, is the way the file command does it. I cannot run a shell command in my use case.
Fabian Jakobs
@Fabian: I'm curious now. What's your use case? It wouldn't be to break down different lines. Does this have to do with encoding or file types?
Xavier Ho
I have a textarea in a web browser and I need to split pasted text into separate lines. Further I want to be able to reassemble the text with the original line breaks.
Fabian Jakobs
+1  A: 

Maybe I'm missing a trick, but couldn't you just open the file as binary and read bytes until you see '\n'? If you saw '\r' just before, it's Windows. Otherwise it's Unix.

Simon Nickerson