LF and CRLF in Text Records

A text format can use one or more bytes as a line ending. Reader settings determine whether those endings appear distinct in decoded strings.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Compare the bytes
  2. Check format-sensitive data
  3. Compare byte offsets with logical newline counts
  4. Preserve bytes when byte-for-byte identity matters

Compare the bytes

The two endings LF and CRLF have hex forms 0A and 0D 0A. A reader using universal newline translation may present both as a newline in text. Use a byte dump to measure the physical representation.

Check format-sensitive data

If an interchange format or archive test requires a particular output sequence, write that convention explicitly. Test a final record without a terminator as well. Iterating over lines explains how that final input is usually seen.[1][2]

Compare byte offsets with logical newline counts

Logical text A followed by B on a new line can appear as 41 0A 42 with LF or 41 0D 0A 42 with CRLF. The second has one more byte before B. A text reader that translates newlines can return the same logical lines for both files. See iterating over lines.

LF form:    B at zero-based byte offset 2
CRLF form:  B at offset 3
Both have the logical lines A and B

Preserve bytes when byte-for-byte identity matters

Checksums and exact file comparisons operate before line-ending translation. Structured text also may allow a newline inside a field. Check both newline conventions, a final line without a terminator and embedded newlines where supported.

References

  1. Python Software Foundation, io: Core Tools for Working with Streams ↩
  2. IETF, RFC 4180: Common Format and MIME Type for CSV Files ↩