In the C standard library, the memchr
function is used to search for a specific character in a memory block. It is a general-purpose memory search function suitable for any type of data.
memchr Function Header
The header file for the memchr
function is <string.h>
. Before using the memchr
function, ensure that you include this header file in your C code:
#include <string.h>
memchr Function Prototype
void *memchr(const void *s, int c, size_t n);
The memchr
function searches for the first occurrence of the character c
(converted to unsigned char
) in the first n
characters of the object pointed to by s
.
Parameter Description
s
: Pointer to the memory block to search;c
: The character value to search for, which is converted tounsigned char
;n
: The number of bytes to search;
Return Value
If memchr
finds the character, it returns a pointer to the located character; if the character is not found, it returns a null pointer NULL
.
memchr Example Code
Calculating the Position of a Character in a Memory Block
By subtracting the starting address of the memory block from the return value of the memchr
function, the offset can be obtained; however, you must also consider the possibility of memchr
returning a null pointer.
#include <stdio.h>
#include <string.h>
int main() {
const char *src = "perfcode.com";
char target_char = '.';
long int offset;
char* target_ptr = memchr(src, target_char, strlen(src));
if (target_ptr == NULL) {
printf("target byte not found.\n");
} else {
offset = target_ptr - src;
printf("offset = %ld\n", offset);
}
return 0;
}
Getting the File Extension
The memchr
function can be used to find delimiters or specific markers, for example, to find field separators in CSV files or other custom formats.
This example is used to get the file extension from a filename:
#include <stdio.h>
#include <string.h>
int main() {
const char* filename = "example.exe";
char* extension = memchr(filename, '.', strlen(filename));
if (extension == NULL) {
printf("The %s file has no extension.\n", filename);
}
else {
printf("The %s file extension is: %s\n", filename, extension);
}
return 0;
}