sscanf(3)

πŸ’– sscanf(3) β€” bestie edition πŸ’–

okay so we're doing sscanf(3) today. yes, the sscanf, vsscanf girlies. input string format conversion. she scans formatted input out of a string and she is LOWKEY iconic for it. sit down, grab a strawberry, we're going through every single line of this thing together, no skips, no skimming. πŸ“βœ¨


πŸ“š LIBRARY

Standard C library (libc, -lc).

ngl bestie you literally just link -lc and you're in. that's the whole vibe. πŸ’…


✨ SYNOPSIS ✨

#include <stdio.h>

int sscanf(const char *restrict str,
           const char *restrict format, ...);

#include <stdarg.h>

int vsscanf(const char *restrict str,
           const char *restrict format, va_list ap);

so the shape is: you hand her a str, you hand her a format, and then you hand her a little parade of pointers and she fills them in. that's the whole deal. 🫢

πŸŽ€ Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

  • vsscanf() β€” you need _ISOC99_SOURCE || _POSIX_C_SOURCE >= 200112L or she simply will not appear. it's giving "you must be this tall to ride". 😭

🌸 DESCRIPTION 🌸

The sscanf() family of functions scans formatted input according to format as described below. That format may contain conversion specifications, and the results from those conversions (if there are any, like, if it actually converted something) get stored in the locations pointed to by the pointer arguments that follow format. And every single pointer argument has to be a type that's actually appropriate for the value returned by the corresponding conversion specification. type mismatch = you did this to yourself, bestie. πŸ™ˆ

If the number of conversion specifications in format exceeds the number of pointer arguments, the results are undefined. no cap. that's not a vibe, that's undefined behavior, and undefined behavior does not care about your feelings. πŸ’€
If the number of pointer arguments exceeds the number of conversion specifications, then the excess pointer arguments are evaluated, but are otherwise ignored. so they get looked at and then ghosted. πŸ‘»

sscanf() β€” these functions read their input from the string pointed to by str. that's the tea. β˜•

The vsscanf() function is analogous to vsprintf(3). she's the va_list-flavored sister, iykyk. 🌈

The format string is literally just a sequence of directives describing how to process the sequence of input characters. And here's the important part: if processing of a directive fails, no further input is read, and sscanf() returns. she stops. she's done. periodt. πŸ›‘

A "failure" can be either of these two girlies:

  • input failure β€” meaning the input characters were simply unavailable.
  • matching failure β€” meaning the input was inappropriate (more on that below).

A directive is one of the following:

  • A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space in the input, including none. so, like, zero whitespace is also fine. she's flexible. πŸ’–
  • An ordinary character (i.e., one other than white space or '%'). This character must exactly match the next character of input. exact. character for character. no exceptions, no "close enough". πŸ’…
  • A conversion specification, which commences with a '%' (percent) character. A sequence of characters from the input is converted according to this specification, and the result gets placed in the corresponding pointer argument. If the next item of input does not match the conversion specification, the conversion fails β€” and that is a matching failure.

Each conversion specification in format begins with either the character '%' or the character sequence "%n$" (see below for the distinction), followed by:

  • An optional '*' assignment-suppression character: sscanf() reads input as directed by the conversion specification, but discards the input. No corresponding pointer argument is required, and this specification is not included in the count of successful assignments returned by sscanf(). she reads it and immediately forgets it. iconic behavior honestly. πŸ’€
  • For decimal conversions, an optional quote character ('). This specifies that the input number may include thousands' separators as defined by the LC_NUMERIC category of the current locale. (See setlocale(3).) And the quote character may come before or after the '*' assignment-suppression character. so she's not picky about ordering here. πŸŽ€
  • An optional 'm' character. This is used with string conversions (%s, %c, %[), and it relieves the caller of the need to allocate a corresponding buffer to hold the input: instead, sscanf() allocates a buffer of sufficient size, and assigns the address of this buffer to the corresponding pointer argument, which should be a pointer to a char * variable (this variable does not need to be initialized before the call). And then β€” bestie, listen β€” the caller should subsequently free(3) this buffer when it is no longer required. she allocated it, YOU free it. that's the deal. don't make her come find you. 🫢
  • An optional decimal integer which specifies the maximum field width. Reading of characters stops either when this maximum is reached or when a nonmatching character is found, whichever happens first. Most conversions discard initial white space characters (the exceptions are noted below), and those discarded characters don't count toward the maximum field width. String input conversions store a terminating null byte ('\0') to mark the end of the input; the maximum field width does not include this terminator. Some conversions require exactly the number of characters specified in the maximum field width, or they just plain fail. she said exact, she meant exact. ✨
  • An optional type modifier character. For example, the l type modifier is used with integer conversions such as %d to specify that the corresponding pointer argument refers to a long rather than a pointer to an int. it's a little "actually, make that bigger" note. πŸ“
  • A conversion specifier that specifies the type of input conversion to be performed. the main character of the whole spec, honestly. πŸ‘‘

The conversion specifications in format come in two forms, either beginning with '%' or beginning with "%n$". And the two forms should not be mixed in the same format string β€” except that a string containing "%n$" specifications can include %% and %*. If format contains '%' specifications, then those correspond in order with successive pointer arguments. In the "%n$" form (which is specified in POSIX.1-2001, but not C99), n is a decimal integer that specifies that the converted input should be placed in the location referred to by the n-th pointer argument following format. so you can point at exactly which argument you mean by number. very "which one of you said that" energy. πŸ‘€

πŸ”₯ Conversions πŸ”₯

The following type modifier characters can appear in a conversion specification:

  • h β€” Indicates that the conversion will be one of d, i, o, u, x, X, or n, and the next pointer is a pointer to a short or unsigned short (rather than int).
  • hh β€” As for h, but the next pointer is a pointer to a signed char or unsigned char. even smol. 🐣
  • j β€” As for h, but the next pointer is a pointer to an intmax_t or a uintmax_t. This modifier was introduced in C99.
  • l β€” Indicates either that the conversion will be one of d, i, o, u, x, X, or n, and the next pointer is a pointer to a long or unsigned long (rather than int), or that the conversion will be one of e, f, or g, and the next pointer is a pointer to double (rather than float). If used with %c or %s, the corresponding parameter is considered as a pointer to a wide character or wide-character string respectively. she multitasks. πŸ’…
  • ll β€” (ell-ell) Indicates that the conversion will be one of b, d, i, o, u, x, X, or n, and the next pointer is a pointer to a long long or unsigned long long (rather than int). two ells, twice the width. πŸ’–
  • L β€” Indicates that the conversion will be either e, f, or g, and the next pointer is a pointer to long double or (as a GNU extension) the conversion will be d, i, o, u, or x, and the next pointer is a pointer to long long. the capital L said "let me be a GNU extension for a sec". 🌈
  • q β€” equivalent to L. This specifier does not exist in ANSI C. so it's the cool underground version. no cap. πŸ’€
  • t β€” As for h, but the next pointer is a pointer to a ptrdiff_t. This modifier was introduced in C99.
  • wN β€” A following integer conversion corresponds to an integer of a width of N bits (C23).
  • z β€” As for h, but the next pointer is a pointer to a size_t. This modifier was introduced in C99.

And the following conversion specifiers are available:

  • % β€” Matches a literal '%'. That is, %% in the format string matches a single input '%' character. No conversion is done (but initial white space characters are discarded), and assignment does not occur. she saw it, she nodded, she moved on. βœ…
  • d β€” Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
  • i β€” Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters that correspond to the base are used. she's doing detective work on the first character and you gotta respect it. πŸ”
  • o β€” Matches an unsigned octal integer; the next pointer must be a pointer to unsigned int.
  • u β€” Matches an unsigned decimal integer; the next pointer must be a pointer to unsigned int.
  • x β€” Matches an unsigned hexadecimal integer (that may optionally begin with a prefix of 0x or 0X, which is discarded); the next pointer must be a pointer to unsigned int.
  • X β€” Equivalent to x.
  • f β€” Matches an optionally signed floating-point number; the next pointer must be a pointer to float.
  • e β€” Equivalent to f.
  • g β€” Equivalent to f.
  • E β€” Equivalent to f.
  • a β€” (C99) Equivalent to f. yes, a is also f. the float girlies have a whole clique. 🌸
  • s β€” Matches a sequence of non-white-space characters; the next pointer must be a pointer to the initial element of a character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first. she will add the '\0' for you, but she will NOT magically make your array big enough. that one's on you. 🫣
  • c β€” Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating null byte is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format. This conversion only succeeds if the number of characters specified by the maximum field can be matched. so: no free '\0', no free whitespace-skipping, and she demands the exact count or nothing at all. diva behavior and honestly? deserved. πŸ’…βœ¨

  • [ β€” okay so this one is the scanset and she is a lot. It matches a nonempty sequence of characters from the set of accepted characters you specify, and the next pointer has to be a pointer to char. Bestie, you've gotta have room for every single character in the string plus a terminating null byte, no shortcuts. Also the usual skip of leading white space is suppressed here β€” no chill, it starts matching immediately. The string gets made up of characters that are in (or, plot twist, not in) a particular set, and that set is defined by everything between the open bracket [ character and a close bracket ] character. The set excludes those characters if the first character after the open bracket is a circumflex (^). Wanna include a close bracket in the set? Make it the very first character after the open bracket or after the circumflex β€” any other position and it just ends the set, periodt. The hyphen character - is also special; when it's placed between two other characters it adds all the intervening characters to the set. To include a literal hyphen, make it the last character before the final close bracket. For instance, [^]0-9-] means the set "everything except close bracket, zero through nine, and hyphen". And the string ends when a character shows up that isn't in the set (or, with a circumflex, is in the set) or when the field width runs out. πŸ’…
  • p β€” matches a pointer value, exactly like what %p prints in printf(3) 🫢. The next pointer has to be a pointer to a pointer to void. Very pointer-to-pointer of it.
  • n β€” nothing is expected here, it's giving observer energy. Instead, the number of characters consumed thus far from the input gets stored through the next pointer, which must be a pointer to int, or a variant whose size matches the (optionally) supplied integer length modifier. Lowkey important: this is not a conversion and it does not increase the count returned by the function. The assignment can be suppressed with the * assignment-suppression character, but the effect on the return value is undefined. Therefore %*n conversions should not be used. Not me warning you twice. πŸ’€

✨ RETURN VALUE ✨

On success, these functions return the number of input items successfully matched and assigned πŸŽ€. This can be fewer than you provided for, or even zero, in the event of an early matching failure. It's giving "we tried our best".

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. 😭


🌸 ERRORS 🌸

  • EILSEQ β€” Input byte sequence does not form a valid character. Rude of it, honestly.
  • EINVAL β€” Not enough arguments; or format is NULL.
  • ENOMEM β€” Out of memory. We've all been there bestie.

πŸ‘‘ ATTRIBUTES πŸ‘‘

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

  • sscanf(), vsscanf() β€” Thread safety: MT-Safe locale

⭐ STANDARDS ⭐

C11, POSIX.1-2008. She's certified, she's official. πŸ’–


πŸ¦‹ HISTORY πŸ¦‹

C89, POSIX.1-2001.

The q specifier is the 4.4BSD notation for long long, while ll or the usage of L in integer conversions is the GNU notation. Two languages, one function, iykyk.

The Linux version of these functions is based on the GNU libio library. Take a look at the info(1) documentation of GNU libc (glibc-1.08) for a more concise description. 🌈


πŸ’œ NOTES πŸ’œ

The 'a' assignment-allocation modifier

Originally, the GNU C library supported dynamic allocation for string inputs (as a nonstandard extension, bestie, keep that in mind) via the a character. This feature is present at least as far back as glibc 2.0. So one could write the following to have sscanf() allocate a buffer for a string, with a pointer to that buffer being returned in *buf:

char *buf;
sscanf(str, "%as", &buf);

The use of the letter a for this purpose was problematic, since a is also specified by the ISO C standard as a synonym for f (floating-point input). POSIX.1-2008 instead specifies the m modifier for assignment allocation (as documented in DESCRIPTION, above). πŸ‘‘

Note that the a modifier is not available if the program is compiled with gcc -std=c99 or gcc -D_ISOC99_SOURCE (unless _GNU_SOURCE is also specified), in which case the a is interpreted as a specifier for floating-point numbers (see above). So like, be careful. πŸ™ˆ

Support for the m modifier was added to glibc 2.7, and new programs should use that modifier instead of a. Glow up.

As well as being standardized by POSIX, the m modifier has the following further advantages over the use of a:

  • It may also be applied to %c conversion specifiers (e.g., %3mc). πŸŽ€
  • It avoids ambiguity with respect to the %a floating-point conversion specifier (and is unaffected by gcc -std=c99 etc.).

πŸ’€ BUGS πŸ’€

Numeric conversion specifiers

Use of the numeric conversion specifiers produces undefined behavior for invalid input. See C11 7.21.6.2/10. This is a bug in the ISO C standard, and not an inherent design issue with the API. However, current implementations are not safe from that bug, so it is not recommended to use them. Instead, programs should use functions such as strtol(3) to parse numeric input. Alternatively, mitigate it by specifying a maximum field width. Not me telling you the whole standard has a flaw 😭 slay of us to survive regardless.

Bestie. For real. Undefined behavior is not a vibe. Do not send it.

Nonstandard modifiers

These functions are fully C99 conformant, but provide the additional modifiers q and a as well as an additional behavior of the L and ll modifiers. The latter may be considered to be a bug, as it changes the behavior of modifiers defined in C99. 🌸

Some combinations of the type modifiers and conversion specifiers defined by C99 do not make sense (e.g., %Ld). While they may have a well-defined behavior on Linux, this need not be so on other systems. Therefore it usually is better to use modifiers that are not defined by C99 at all, that is, use q instead of L in combination with d, i, o, u, x, and X conversions or ll. πŸ’…

The usage of q is not the same as on 4.4BSD, as it may be used in float conversions equivalently to L.


πŸ“ EXAMPLES πŸ“

To use the dynamic allocation conversion specifier, specify m as a length modifier (thus %ms or %m[range]). The caller must free(3) the returned string, as in the following example:

char *p;
int n;

errno = 0;
n = sscanf(str, "%m[a-z]", &p);
if (n == 1) {
    printf("read: %s\n", p);
    free(p);
} else if (errno != 0) {
    perror("sscanf");
} else {
    fprintf(stderr, "No matching characters\n");
}

As shown in the above example, it is necessary to call free(3) only if the sscanf() call successfully read a string. Every other path and you're just leaking nothing, we love a conditional cleanup. 🫢


🌈 SEE ALSO 🌈

getc(3), printf(3), setlocale(3), strtod(3), strtol(3), strtoul(3)


That's a wrap bestie!! πŸŽ‰ This page is from Linux man-pages 6.20, dated 2026-02-16 β€” and yes I'm mentioning the date in my sign-off because it's iconic of me. Now go parse something. πŸ’–βœ¨πŸ‘‘

πŸ“¦ 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: BSD-4-Clause-UC
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms