Last active
May 24, 2023 03:58
-
-
Save 61131/a4d5846dd2fb4aaa22ecf9e05a3b34a1 to your computer and use it in GitHub Desktop.
strlcat and strlcpy functions derived from OpenBSD libc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
size_t | |
strlcat(char *dst, const char *src, size_t dsize) { | |
const char *odst = dst; | |
const char *osrc = src; | |
size_t count = dsize; | |
size_t length; | |
if ((dst == NULL) || | |
(src == NULL)) { | |
return 0; | |
} | |
while ((count-- != 0) && | |
(*dst != '\0')) { | |
dst++; | |
} | |
length = dst - odst; | |
count = dsize - length; | |
if (count-- == 0) { | |
return (length + strlen(src)); | |
} | |
while (*src != '\0') { | |
if (count != 0) { | |
*dst++ = *src; | |
count--; | |
} | |
src++; | |
} | |
*dst = '\0'; | |
return (length + (src - osrc)); | |
} | |
size_t | |
strlcpy(char *dst, const char *src, size_t dsize) { | |
const char *osrc = src; | |
size_t count = dsize; | |
if ((dst == NULL) || | |
(src == NULL)) { | |
return 0; | |
} | |
if (count != 0) { | |
while (--count != 0) { | |
if ((*dst++ = *src++) == '\0') { | |
break; | |
} | |
} | |
} | |
if (count == 0) { | |
if (dsize != 0) { | |
*dst = '\0'; | |
} | |
while (*src++); | |
} | |
return (src - osrc - 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment