问题
I have a Linux system and Windows system send text to each other and each one of them update a text file with the received text, now i have a problem when the text contain LF/CR char, i need to unify the newline char sent by both of them, i tried to use only \n (replacing \r by empty string before sending the string) but it doesn't work , is there a known solution for this issue ?
回答1:
Don't unifying, just accommodate for it in every environment, like Git does.
When sending from Windows to Linux replace \r\n "CRLF" with \n "LF" and vice versa, when sending from Linux to Windows convert \n to \r\n.
回答2:
How to deal with newline char across different platforms
It depends on the platform and standard, but the best rule of thumb I have found is: during reading handle all of them; and write according to a standard or the host platform conventions.
The early RFCs, like Email, Privacy Enhanced Email (PEM), Telnet, etc used '\r\n'
a.k.a Windows line endings. So all Unix, OS X and Linux systems should be able to handle them.
Some RFCs say to write in a particular format. If that is the case, then you do what the standard says. For example, Telnet and Email RFCs say software will write '\r\n'
. As another example, the SSH file format RFC says to write in the host's format. So software on Windows writes '\r\n'
, on Linux writes '\n'
and on OS X writes '\r'
.
In the absence of a standard write the platform's native format. Software on Windows writes '\r\n'
, on Linux writes '\n'
and on OS X writes '\r'
. And because of your rule of thumb - read all formats - the receiving software should be able to parse it.
I know you cannot trust some standard libraries and runtimes, so you may need to write your own readline
function that greedy matches \r\n
. Sadly, this is the case with the C++ runtime on Linux. On Linux in a C++ program, the C++ runtime will see this as one line, not two: Hello\rWorld\n
. Grep will also fall on its face if you search for \r$
.
来源:https://stackoverflow.com/questions/17192426/how-to-deal-with-newline-char-across-different-platforms