libc: Add strcmp() and strncmp()

This commit is contained in:
apio 2022-10-15 12:30:49 +02:00
parent 3e2a4276e9
commit 3fde7e46f5
2 changed files with 27 additions and 0 deletions

View File

@ -50,6 +50,12 @@ extern "C"
/* Concatenates at most max bytes of the string src into dest. */ /* Concatenates at most max bytes of the string src into dest. */
char* strncat(char* dest, const char* src, size_t max); char* strncat(char* dest, const char* src, size_t max);
/* Compares strings a and b. You might prefer to use the safer strncmp function. */
int strcmp(const char* a, const char* b);
/* Compares at most max bytes of the strings a and b. */
int strncmp(const char* a, const char* b, size_t max);
/* Returns the error string associated with the error number err. */ /* Returns the error string associated with the error number err. */
char* strerror(int err); char* strerror(int err);

View File

@ -81,6 +81,27 @@ extern "C"
return dest; return dest;
} }
int strcmp(const char* a, const char* b)
{
while (*a && (*a == *b))
{
a++;
b++;
}
return *(const unsigned char*)a - *(const unsigned char*)b;
}
int strncmp(const char* a, const char* b, size_t max)
{
const char* base = a;
while (*a && (*a == *b) && (size_t)(a - base) < (max - 1))
{
a++;
b++;
}
return *(const unsigned char*)a - *(const unsigned char*)b;
}
char* strcat(char* dest, const char* src) char* strcat(char* dest, const char* src)
{ {
size_t dest_len = strlen(dest); size_t dest_len = strlen(dest);