Posts

    Stop fearing the regex!

    Not kidding! Developers fear the regex. And yeah, I get it. They look ugly. But they are powerful. And it is way more hard to read them than to write them. Which is not ideal. But at least you can benefit from writing a regex here and there. Probably document them in-code with a meaningful comment for your future self and you’ll be fine. Learning to write some basic, simple yet powerful regex is not impossible and I’m writing this post to prove that.

    UTF-8 string character count in C/C++

    The following code defines, tests and illustrates the use of utf8len() function. Which is a small piece of code for counting characters in UTF-8 (multibyte) string. Compile this example with GCC by running: $ gcc utf8len.c -lrt -o utf8len The RT library is used for the high precision clock only, you don’t need to link it if you are using the function itself into your own code. This utf8len() function provides a portable (and small footprint) way of counting UTF-8 charactes in standard C or C++.

    Get the local MAC address in C/C++

    This code snippet shows how to get the local MAC (hardware) address in POSIX systems. It should work in Windows too, using Cygwin or similar. #include <netdb.h>#include <unistd.h>#include <string.h>#include <sys/fcntl.h>#include <sys/errno.h>#include <sys/ioctl.h>#include <sys/socket.h>#include <arpa/inet.h>#include <net/if.h>#include <stdio.h> int main(int argc, char ** argv) { struct ifreq ifr; int s; if ((s = socket(AF_INET, SOCK_STREAM,0)) < 0) { perror("socket"); return -1; } strcpy(ifr.ifr_name, argv[1]); if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0) { perror("ioctl"); return -1; } unsigned char *hwaddr = (unsigned char *)ifr.