我知道換行和回車的區別。回車將游標移動到行首,換行將游標移動到下一個而不是該行的開頭。但是在使用換行符時,游標不會轉到下一行的開頭嗎?那么為什么人們說 lf 只將游標移動到下一行而不去開始,而 crlf 去到該行的開頭,然后去到下一行。使用C等任何編程語言列印“Hello\nHELLO”時,是否會在下一行的開頭自動列印HELLO?那么CRLF和LF有什么區別呢?
uj5u.com熱心網友回復:
DOS 使用回車和換行\r\n作為行尾,而 UNIX 只使用換行\n。沒有更多要講的了......除了例如。dos2unix洗掉所有\r,或者也cat -v將輸出行尾。
uj5u.com熱心網友回復:
這是令人困惑的,因為 Windows 和 Unix 對它們的行為不同:
linux-$ printf "abc\ndefg\rhij\r\n" | hexdump -C
00000000 61 62 63 0a 64 65 66 67 0d 68 69 6a 0d 0a |abc.defg.hij..|
0000000e
如您所見,程式只是按照指示將這些字符(0x0d - CR、0x0a - LF)發送到管道 ( | hexdump -C)、檔案(您將使用dos2unix或 的位置unix2dos)或終端。
如果我們將其發送到終端,那么您就會開始看到不同之處:
linux-$ printf "abc\ndefg\rhij\r\n"
abc
hijg
這是來自 Linux 上的 URXVT,它被配置為使用常規的 Unix 約定(與語意不同)。
在這個約定中,\n被終端視為\r\n,因此abc\ndefg\rhij\r\n實際上變成abc\ndefg\r\nhij\r\n。
這就是為什么當終端顯示它時,它列印abc,回傳到行首,下降到下一行,列印defg,回傳到行首,不下降到下一行,用hij,然后回傳到該行的開頭,并下降到下一行。
因此,要回答您的具體問題:
但是在使用換行符時,游標不會轉到下一行的開頭嗎?
“游標”假定處理輸出的設備是終端。所以答案取決于終端的配置方式。在 Unix 終端上答案是“是”。Windows 和 DOS 終端未配置為執行此操作。
那么為什么人們說 lf 只將游標移動到下一行而不去開始,而 crlf 去到該行的開頭,然后去到下一行。
因為這就是 Windows 和 DOS 終端處理 LF 和 CRLF 的方式。
使用C等任何編程語言列印“Hello\nHELLO”時,是否會在下一行的開頭自動列印HELLO?
啊,現在這是一個很好的問題。有一個鬼鬼祟祟的小規則有:
在文本模式下寫入檔案、設備節點或套接字/fifo 時,
\n會透明地轉換為系統使用的本機換行序列,該序列可能長于一個字符。在文本模式下閱讀時,本機換行序列被轉換回\n. 在二進制模式下,不進行翻譯,\n直接輸出由 產生的內部表示。
你看,Unix 終端上的約定(即默認配置)是將\n視為\r\n,因此Hello\nHELLO從 C發送到 Unix 終端將導致它在遇到 時也回傳到行首\n。
On Windows, on the other hand, all these print functions silently translate your input \n to the output \r\n, and the terminal treats each of them separately as you'd expect.
On old Macs, where newline was \r, \n was silently translated to \r, and the terminal drops to the next line when it returns the cursor to the beginning of the line.
Then how is there difference between CRLF and LF?
- LF is the programming language standard for "new line" across all systems whereas CR is an artifact of the program that displays the text, usually a terminal.
- Some systems (Windows) silently translate LF to CRLF in some situations, but treat CR regularly.
- Some systems (old Macs) silently translate CR to CRLF in some situations, but treat LF regularly.
- Some terminals (Unix) treat LF as CRLF, but treat CR regularly.
- Some terminals (old Macs) treat CR as CRLF, but treat LF regularly.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/357969.html
