file-handling · beginner · ~10 min

Convert CRLF to LF

Stream-rewrite a buffer while changing its length safely.

Challenge

Your job

int normalize_eol(const char *in, char *out, size_t cap);

Copy in to out, replacing every \r\n with a single \n and dropping any lone \r. NUL-terminate. Return bytes written, or -1 on NULL/overflow.

Hints

  1. Walk in; skip \r when the next char is \n (or always, for lone \r).
  2. Check cap before each write.

Why this matters

Windows files arrive with CRLF; normalising to LF avoids the stray '\r' bugs that plague cross-platform text handling.

Starter code

#include <stddef.h>
int normalize_eol(const char *in, char *out, size_t cap) {
    /* TODO */
    (void)in; (void)out; (void)cap;
    return -1;
}

Common mistakes

Only handling CRLF and leaving lone CRs. Forgetting the NUL's byte in the cap check.

Edge cases to handle

Already-LF text is unchanged. A lone CR is removed. Tiny output buffer.

Complexity

O(n).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.