A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
memccpy copies bytes from source to destination, stopping when it either copies n bytes or encounters a specified delimiter byte, whichever comes first. If the delimiter is found, it is copied and memccpy returns a pointer to the byte after the delimiter in the destination. If not found, it returns NULL. This is useful for copying protocol fields, path components, or any bounded data terminated by a known byte.
#include <stdio.h>#include <string.h>int main(void) {const char *input = "key=value;next=field";char output[32];memset(output, 0, sizeof(output));void *result = memccpy(output, input, '=', sizeof(output) - 1);if (result) {printf("Delimiter found. Copied: \"%s\"\n", output);printf("Remaining input starts at: \"%s\"\n",input + ((char *)result - output));} else {printf("Delimiter not found. Copied: \"%s\"\n", output);}return 0;}
memccpy copied "key=" including the delimiter. The return value points to the byte after '=' in the output buffer. By computing the offset, we can find where the remaining input starts. This is a clean way to split a key=value pair without modifying the input or calling strchr separately.
memccpy is a POSIX function, not ISO C. It is available on Linux, macOS, and BSD. On Windows, use _memccpy from string.h. It fills a niche between memcpy (no delimiter awareness) and strncpy (null-terminator awareness). Next: memchr, for searching a byte pattern in raw memory.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.