file-handling · beginner · ~10 min
Stream-rewrite a buffer while changing its length safely.
Normalize Windows-style line endings to Unix: turn every \r\n into a single \n and drop stray \r bytes, avoiding the cross-platform bugs they cause.
Implement int normalize_eol(const char *in, char *out, size_t cap) that copies in to out (NUL-terminated), replacing each \r\n with \n and removing any lone \r.
in: NUL-terminated source text.out / cap: destination buffer and its size.Return the number of bytes written to out. Return -1 if in/out is NULL or the result doesn't fit in cap.
normalize_eol("a\r\nb\r\n", out, 64) -> 4, out = "a\nb\n"
normalize_eol("plain\n", out, 64) -> out = "plain\n" (unchanged)
normalize_eol("x\ry", out, 64) -> out = "xy" (lone CR dropped)
\r (not followed by \n) is removed.cap before each write. (Hint: dropping every \r handles both CRLF and lone CR.)Windows files arrive with CRLF; normalising to LF avoids the stray '\r' bugs that plague cross-platform text handling.
in: NUL-terminated source text. out/cap: result buffer and size.
int bytes written to out, or -1 on NULL / overflow.
Convert CRLF to LF and drop lone CR; bound each write by cap.
#include <stddef.h>
int normalize_eol(const char *in, char *out, size_t cap) {
/* TODO */
(void)in; (void)out; (void)cap;
return -1;
}
Only handling CRLF and leaving lone CRs. Forgetting the NUL's byte in the cap check.
Already-LF text is unchanged. A lone CR is removed. Tiny output buffer.
O(n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.