NAME |LIBRARY |SYNOPSIS |DESCRIPTION |RETURN VALUE |ERRORS |ATTRIBUTES |STANDARDS |HISTORY |NOTES |BUGS |EXAMPLES |SEE ALSO |COLOPHON | |
sscanf(3) Library Functions Manualsscanf(3)sscanf, vsscanf - input string format conversion
Standard C library (libc,-lc)
#include <stdio.h>int sscanf(const char *restrictstr,const char *restrictformat, ...);#include <stdarg.h>int vsscanf(const char *restrictstr,const char *restrictformat, va_listap); Feature Test Macro Requirements for glibc (seefeature_test_macros(7)):vsscanf(): _ISOC99_SOURCE || _POSIX_C_SOURCE >= 200112L
Thesscanf() family of functions scans formatted input according toformat as described below. This format may containconversionspecifications; the results from such conversions, if any, are stored in the locations pointed to by thepointer arguments that followformat. Eachpointer argument must be of a type that is appropriate for the value returned by the corresponding conversion specification. If the number of conversion specifications informat exceeds the number ofpointer arguments, the results are undefined. If the number ofpointer arguments exceeds the number of conversion specifications, then the excesspointer arguments are evaluated, but are otherwise ignored.sscanf() These functions read their input from the string pointed to bystr. Thevsscanf() function is analogous tovsprintf(3). Theformat string consists of a sequence ofdirectives which describe how to process the sequence of input characters. If processing of a directive fails, no further input is read, andsscanf() returns. A "failure" can be either of the following:input failure, meaning that input characters were unavailable, ormatching failure, meaning that the input was inappropriate (see below). A directive is one of the following: • A sequence of white-space characters (space, tab, newline, etc.; seeisspace(3)). This directive matches any amount of white space, including none, in the input. • An ordinary character (i.e., one other than white space or '%'). This character must exactly match the next character of input. • 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 is placed in the correspondingpointer argument. If the next item of input does not match the conversion specification, the conversion fails—this is amatchingfailure. Eachconversion specification informat 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 correspondingpointer argument is required, and this specification is not included in the count of successful assignments returned bysscanf(). • For decimal conversions, an optional quote character ('). This specifies that the input number may include thousands' separators as defined by theLC_NUMERICcategory of the current locale. (Seesetlocale(3).) The quote character may precede or follow the '*' assignment-suppression character. • An optional 'm' character. This is used with string conversions (%s,%c,%[), and 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 correspondingpointer argument, which should be a pointer to achar * variable (this variable does not need to be initialized before the call). The caller should subsequentlyfree(3) this buffer when it is no longer required. • An optional decimal integer which specifies themaximumfield 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 these 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. • An optionaltype modifier character. For example, thel type modifier is used with integer conversions such as%d to specify that the correspondingpointer argument refers to along rather than a pointer to anint. • Aconversion specifier that specifies the type of input conversion to be performed. The conversion specifications informat are of two forms, either beginning with '%' or beginning with "%n$". The two forms should not be mixed in the sameformat string, except that a string containing "%n$" specifications can include%%and%*. Ifformat contains '%' specifications, then these correspond in order with successivepointer 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 then-thpointer argument followingformat.Conversions The followingtype modifier characters can appear in a conversion specification:hIndicates that the conversion will be one ofd,i,o,u,x,X, orn, and the next pointer is a pointer to ashort orunsigned short (rather thanint).hhAs forh, but the next pointer is a pointer to asignedchar orunsigned char.jAs forh, but the next pointer is a pointer to anintmax_t or auintmax_t. This modifier was introduced in C99.lIndicates either that the conversion will be one ofd,i,o,u,x,X, orn, and the next pointer is a pointer to along orunsigned long (rather thanint), or that the conversion will be one ofe,f, org, and the next pointer is a pointer todouble (rather thanfloat). If used with%cor%s, the corresponding parameter is considered as a pointer to a wide character or wide-character string respectively.ll(ell-ell) Indicates that the conversion will be one ofb,d,i,o,u,x,X, orn, and the next pointer is a pointer to along long orunsigned long long (rather thanint).LIndicates that the conversion will be eithere,f, org, and the next pointer is a pointer tolong double or (as a GNU extension) the conversion will bed,i,o,u, orx, and the next pointer is a pointer tolong long.qequivalent toL. This specifier does not exist in ANSI C.tAs forh, but the next pointer is a pointer to aptrdiff_t. This modifier was introduced in C99.zAs forh, but the next pointer is a pointer to asize_t. This modifier was introduced in C99. The followingconversion 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.dMatches an optionally signed decimal integer; the next pointer must be a pointer toint.iMatches an optionally signed integer; the next pointer must be a pointer toint. The integer is read in base 16 if it begins with0x or0X, in base 8 if it begins with0, and in base 10 otherwise. Only characters that correspond to the base are used.oMatches an unsigned octal integer; the next pointer must be a pointer tounsigned int.uMatches an unsigned decimal integer; the next pointer must be a pointer tounsigned int.xMatches an unsigned hexadecimal integer (that may optionally begin with a prefix of0x or0X, which is discarded); the next pointer must be a pointer tounsignedint.XEquivalent tox.fMatches an optionally signed floating-point number; the next pointer must be a pointer tofloat.eEquivalent tof.gEquivalent tof.EEquivalent tof.a(C99) Equivalent tof.sMatches 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.cMatches a sequence of characters whose length is specified by themaximum field width (default 1); the next pointer must be a pointer tochar, 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.[Matches a nonempty sequence of characters from the specified set of accepted characters; the next pointer must be a pointer tochar, and there must be enough room for all the characters in the string, plus a terminating null byte. The usual skip of leading white space is suppressed. The string is to be made up of characters in (or not in) a particular set; the set is defined by the characters between the open bracket[character and a close bracket] character. The setexcludes those characters if the first character after the open bracket is a circumflex (^). To include a close bracket in the set, make it the first character after the open bracket or the circumflex; any other position will end the set. The hyphen character-is also special; when placed between two other characters, it adds all intervening characters to the set. To include a 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". The string ends with the appearance of a character not in the (or, with a circumflex, in) set or when the field width runs out.pMatches a pointer value (as printed by%pinprintf(3)); the next pointer must be a pointer to a pointer tovoid.nNothing is expected; instead, the number of characters consumed thus far from the input is stored through the next pointer, which must be a pointer toint, or variant whose size matches the (optionally) supplied integer length modifier. This isnot a conversion and doesnot 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.On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure. The valueEOFis returned if the end of input is reached before either the first successful conversion or a matching failure occurs.
EILSEQInput byte sequence does not form a valid character.EINVALNot enough arguments; orformat is NULL.ENOMEMOut of memory.
For an explanation of the terms used in this section, seeattributes(7). ┌───────────────────────────────┬───────────────┬────────────────┐ │Interface│Attribute│Value│ ├───────────────────────────────┼───────────────┼────────────────┤ │sscanf(),vsscanf() │ Thread safety │ MT-Safe locale │ └───────────────────────────────┴───────────────┴────────────────┘
C11, POSIX.1-2008.
C89, POSIX.1-2001. Theqspecifier is the 4.4BSD notation forlong long, whilellor the usage ofLin integer conversions is the GNU notation. The Linux version of these functions is based on theGNU libio library. Take a look at theinfo(1) documentation ofGNU libc(glibc-1.08) for a more concise description.
The 'a' assignment-allocation modifier Originally, the GNU C library supported dynamic allocation for string inputs (as a nonstandard extension) via theacharacter. (This feature is present at least as far back as glibc 2.0.) Thus, one could write the following to havesscanf() 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 letterafor this purpose was problematic, sincea is also specified by the ISO C standard as a synonym forf (floating-point input). POSIX.1-2008 instead specifies them modifier for assignment allocation (as documented in DESCRIPTION, above). Note that theamodifier is not available if the program is compiled withgcc -std=c99 orgcc -D_ISOC99_SOURCE (unless_GNU_SOURCEis also specified), in which case theais interpreted as a specifier for floating-point numbers (see above). Support for themmodifier was added to glibc 2.7, and new programs should use that modifier instead ofa. As well as being standardized by POSIX, themmodifier has the following further advantages over the use ofa: • It may also be applied to%cconversion specifiers (e.g.,%3mc). • It avoids ambiguity with respect to the%afloating-point conversion specifier (and is unaffected bygcc -std=c99 etc.).
Numeric conversion specifiers Use of the numeric conversion specifiers produces undefined behavior for invalid input. See C11 7.21.6.2/10 ⟨https://port70.net/%7Ensz/c/c11/n1570.html#7.21.6.2p10⟩. 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 asstrtol(3) to parse numeric input. Alternatively, mitigate it by specifying a maximum field width.Nonstandard modifiers These functions are fully C99 conformant, but provide the additional modifiersqandaas well as an additional behavior of theLandllmodifiers. 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 to be so on other systems. Therefore it usually is better to use modifiers that are not defined by C99 at all, that is, useqinstead ofLin combination withd,i,o,u,x, andXconversions orll. The usage ofqis not the same as on 4.4BSD, as it may be used in float conversions equivalently toL.
To use the dynamic allocation conversion specifier, specifymas a length modifier (thus%msor%m[range]). The caller mustfree(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 callfree(3) only if thesscanf() call successfully read a string.getc(3),printf(3),setlocale(3),strtod(3),strtol(3),strtoul(3)
This page is part of theman-pages (Linux kernel and C library user-space interface documentation) project. Information about the project can be found at ⟨https://www.kernel.org/doc/man-pages/⟩. If you have a bug report for this manual page, see ⟨https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git/tree/CONTRIBUTING⟩. This page was obtained from the tarball man-pages-6.15.tar.gz fetched from ⟨https://mirrors.edge.kernel.org/pub/linux/docs/man-pages/⟩ on 2025-08-11. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up- to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which isnot part of the original manual page), send a mail to man-pages@man7.orgLinux man-pages 6.15 2025-05-17sscanf(3)Pages that refer to this page:curs_scanw(3x), scanf(3), stdio(3)
HTML rendering created 2025-09-06 byMichael Kerrisk, author ofThe Linux Programming Interface. For details of in-depthLinux/UNIX system programming training courses that I teach, lookhere. Hosting byjambit GmbH. | ![]() |