snprintf(3)

πŸ’– snprintf(3) β€” string print formatted πŸ’–

okay bestie, listen up, we're doing snprintf and vsnprintf from the Library Functions Manual and honestly? they're giving "write to a string instead of a stream" and I'm obsessed.


✨ NAME ✨

snprintf, vsnprintf β€” string print formatted πŸŽ€

πŸ“š LIBRARY πŸ“š

Standard C library (libc, -lc) 🫢

🌸 SYNOPSIS 🌸

#include <stdio.h>

int snprintf(size_t size;
            char str[restrict size], size_t size,
            const char *restrict format, ...);
int vsnprintf(size_t size;
            char str[restrict size], size_t size,
            const char *restrict format, va_list ap);

🧚 Feature Test Macro Requirements for glibc (see feature_test_macros(7)) 🧚

snprintf(), vsnprintf():

_XOPEN_SOURCE >= 500 || _ISOC99_SOURCE
    || /* glibc <= 2.19: */ _BSD_SOURCE

πŸ’… DESCRIPTION πŸ’…

So these functions are basically printf(3)'s cousins β€” same energy, different target. Instead of writing to a stream, they write to the character string str. no cap. ✨

The functions snprintf() and vsnprintf() write at most size bytes (and yes, that count includes the terminating null byte, '\0') to str. queen behavior.

vsnprintf() is equivalent to snprintf(), except it gets called with a va_list instead of a variable number of arguments. ⚠️ Heads up: this function does not call the va_end macro. And because it invokes the va_arg macro, the value of ap is undefined after the call. Go read stdarg(3) for the whole tea.

C99 and POSIX.1-2001 specify that the results are undefined if a call to snprintf() or vsnprintf() would cause copying to take place between objects that overlap (like, if the target string array and one of the supplied input arguments refer to the same buffer). πŸ’€ See CAVEATS below. fr fr.

πŸ“ Format of the format string πŸ“

See printf(3). that's it, that's the section, bye πŸ’œ


πŸ”₯ RETURN VALUE πŸ”₯

Upon successful return, these functions return the number of bytes printed (excluding the null byte used to end output to strings). ✨

The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte, '\0'). If the output got truncated because of that limit, then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available. So a return value of size or more means your output was truncated. 😭 (See also below under CAVEATS.)

On error, a negative value is returned, and errno is set to indicate the error. πŸ™ˆ


🚨 ERRORS 🚨

See printf(3).


🌈 ATTRIBUTES 🌈

For an explanation of the terms used in this section, see attributes(7).

  • Interface: snprintf(), vsnprintf()
  • Attribute: Thread safety
  • Value: MT-Safe locale πŸ‘‘

πŸ‘‘ STANDARDS πŸ‘‘

C11, POSIX.1-2008.

πŸ¦‹ HISTORY πŸ¦‹

SUSv2, C99, POSIX.1-2001.

Concerning the return value, SUSv2 and C99 contradict each other: when snprintf() is called with size=0 then SUSv2 stipulates an unspecified return value less than 1, while C99 allows str to be NULL in this case, and gives the return value (as always) as the number of characters that would have been written in case the output string has been large enough. POSIX.1-2001 and later align their specification of snprintf() with C99. the drama of it all πŸ’…


⚠️ CAVEATS ⚠️

Some programs imprudently rely on code such as the following:

snprintf(buf, countof(buf), "%s some further text", buf);

to append text to buf. However, the standards explicitly note that the results are undefined if source and destination buffers overlap when calling snprintf() and vsnprintf(). Depending on the version of gcc(1) used, and the compiler options employed, calls such as the above will not produce the expected results. 🫠 so like. don't.

The glibc implementation of snprintf() and vsnprintf() conforms to the C99 standard, that is, behaves as described above, since glibc 2.1. Until glibc 2.0.6, they would return -1 when the output was truncated. throwback behavior, ngl.

πŸ› BUGS πŸ›

See printf(3).


πŸ’‘ EXAMPLES πŸ’‘

To allocate a sufficiently large string and print into it (code correct for both glibc 2.0 and glibc 2.1):

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

char *
make_message(const char *fmt, ...)
{
    int n = 0;
    size_t size = 0;
    char *p = NULL;
    va_list ap;

    /* Determine required size.  */

    va_start(ap, fmt);
    n = vsnprintf(p, size, fmt, ap);
    va_end(ap);

    if (n < 0)
        return NULL;

    size = (size_t) n + 1;      /* One extra byte for '\0' */
    p = malloc(size);
    if (p == NULL)
        return NULL;

    va_start(ap, fmt);
    n = vsnprintf(p, size, fmt, ap);
    va_end(ap);

    if (n < 0) {
        free(p);
        return NULL;
    }

    return p;
}

If truncation occurs in glibc versions prior to glibc 2.0.6, this is treated as an error instead of being handled gracefully. 😭 iconic of them honestly.


🫢 SEE ALSO 🫢

printf(1), asprintf(3), printf(3), puts(3), scanf(3), setlocale(3), strfromd(3), wcrtomb(3), wprintf(3), locale(5)


and that's the whole page, bestie πŸ’– this lil number came from the Linux man-pages 6.20, dated 2025-12-07, and it's the snprintf(3) page. stay safe, don't overlap your buffers, and go forth and format. periodt. πŸ’…πŸŽ€βœ¨

πŸ“¦ where this page comes from
  • arch rolling: man-pages 6.20-1 Β· BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
  • nixpkgs unstable: man-pages 6.20
  • πŸ“œ the page's license: GPL-2.0-or-later
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms