I am writing a C extension for PHP and there I have to build up a string based on some substrings. Currently it looks like this:
spprintf(
&bucket_list_url,
strlen(host) + 1 + sizeof(port) + 1 + strlen(prefix) +strlen("?buckets=true"),
"%s:%d/%s?buckets=true",
host,
port,
prefix
);
It works, but looks horrible and is possibly difficult to maintain. Is there a more cleaner way for safely concatenating these strings together?
I am a beginner in C, as you’ve probably noticed, so I couldn’t come up with any cleaner solution so far.
If you’re using the GNU C runtime (glibc), you can use the
asprintf(3)function to format a string to a dynamically allocated buffer. That way, you don’t have to worry about having a large enough buffer. For example:If you’re not using glibc, you can still use
snprintf(3), but you have to guess at the buffer length. If you guess wrong, you have to allocate a bigger buffer and try again.