1SCANF(3)                   Linux Programmer's Manual                  SCANF(3)
2
3
4

NAME

6       scanf,  fscanf, sscanf, vscanf, vsscanf, vfscanf - input format conver‐
7       sion
8

SYNOPSIS

10       #include <stdio.h>
11
12       int scanf(const char *format, ...);
13       int fscanf(FILE *stream, const char *format, ...);
14       int sscanf(const char *str, const char *format, ...);
15
16       #include <stdarg.h>
17
18       int vscanf(const char *format, va_list ap);
19       int vsscanf(const char *str, const char *format, va_list ap);
20       int vfscanf(FILE *stream, const char *format, va_list ap);
21
22   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
23
24       vscanf(), vsscanf(), vfscanf():
25           _ISOC99_SOURCE || _POSIX_C_SOURCE >= 200112L
26

DESCRIPTION

28       The scanf() family of functions scans  input  according  to  format  as
29       described  below.   This  format may contain conversion specifications;
30       the results from such conversions, if any, are stored in the  locations
31       pointed  to  by the pointer arguments that follow format.  Each pointer
32       argument must be of a type that is appropriate for the  value  returned
33       by the corresponding conversion specification.
34
35       If the number of conversion specifications in format exceeds the number
36       of pointer arguments, the results are  undefined.   If  the  number  of
37       pointer arguments exceeds the number of conversion specifications, then
38       the excess pointer arguments are evaluated, but are otherwise ignored.
39
40       The scanf() function reads input from the standard input stream  stdin,
41       fscanf() reads input from the stream pointer stream, and sscanf() reads
42       its input from the character string pointed to by str.
43
44       The vfscanf() function is analogous to vfprintf(3) and reads input from
45       the  stream  pointer  stream using a variable argument list of pointers
46       (see stdarg(3).  The vscanf() function scans a variable  argument  list
47       from  the  standard  input  and  the vsscanf() function scans it from a
48       string; these are analogous to the vprintf(3) and vsprintf(3) functions
49       respectively.
50
51       The  format  string consists of a sequence of directives which describe
52       how to process the sequence of input characters.  If  processing  of  a
53       directive  fails,  no  further  input  is read, and scanf() returns.  A
54       "failure" can be either of the following: input failure,  meaning  that
55       input  characters  were  unavailable, or matching failure, meaning that
56       the input was inappropriate (see below).
57
58       A directive is one of the following:
59
60       ·      A sequence of white-space characters (space, tab, newline, etc.;
61              see  isspace(3)).   This  directive  matches any amount of white
62              space, including none, in the input.
63
64       ·      An ordinary character (i.e., one other than white space or '%').
65              This character must exactly match the next character of input.
66
67       ·      A conversion specification, which commences with a '%' (percent)
68              character.  A sequence of characters from the input is converted
69              according to this specification, and the result is placed in the
70              corresponding pointer argument.  If the next item of input  does
71              not  match  the  conversion specification, the conversion fails—
72              this is a matching failure.
73
74       Each conversion specification in format begins with either the  charac‐
75       ter '%' or the character sequence "%n$" (see below for the distinction)
76       followed by:
77
78       ·      An optional '*' assignment-suppression character: scanf()  reads
79              input  as directed by the conversion specification, but discards
80              the input.  No corresponding pointer argument is  required,  and
81              this  specification  is  not included in the count of successful
82              assignments returned by scanf().
83
84       ·      For decimal conversions, an optional quote character (').   This
85              specifies  that  the input number may include thousands' separa‐
86              tors as defined  by  the  LC_NUMERIC  category  of  the  current
87              locale.  (See setlocale(3).)  The quote character may precede or
88              follow the '*' assignment-suppression character.
89
90       ·      An optional 'm' character.  This is used with string conversions
91              (%s,  %c, %[), and relieves the caller of the need to allocate a
92              corresponding buffer to hold the input: instead,  scanf()  allo‐
93              cates  a  buffer  of sufficient size, and assigns the address of
94              this buffer to the corresponding pointer argument, which  should
95              be  a  pointer to a char * variable (this variable does not need
96              to be initialized before the call).  The  caller  should  subse‐
97              quently free(3) this buffer when it is no longer required.
98
99       ·      An  optional  decimal  integer which specifies the maximum field
100              width.  Reading of characters stops either when this maximum  is
101              reached or when a nonmatching character is found, whichever hap‐
102              pens first.  Most conversions discard initial white space  char‐
103              acters  (the  exceptions  are  noted below), and these discarded
104              characters don't count toward the maximum field  width.   String
105              input  conversions  store a terminating null byte ('\0') to mark
106              the end of the input; the maximum field width does  not  include
107              this terminator.
108
109       ·      An  optional  type  modifier character.  For example, the l type
110              modifier is used with integer conversions such as %d to  specify
111              that  the  corresponding  pointer  argument refers to a long int
112              rather than a pointer to an int.
113
114       ·      A conversion specifier that specifies the type of input  conver‐
115              sion to be performed.
116
117       The conversion specifications in format are of two forms, either begin‐
118       ning with '%' or beginning with "%n$".  The two  forms  should  not  be
119       mixed  in the same format string, except that a string containing "%n$"
120       specifications can include %% and %*.  If format contains '%'  specifi‐
121       cations,  then  these correspond in order with successive pointer argu‐
122       ments.  In the "%n$" form (which is specified in POSIX.1-2001, but  not
123       C99),  n  is  a decimal integer that specifies that the converted input
124       should be placed in the location referred to by the n-th pointer  argu‐
125       ment following format.
126
127   Conversions
128       The following type modifier characters can appear in a conversion spec‐
129       ification:
130
131       h      Indicates that the conversion will be one of d, i, o, u,  x,  X,
132              or  n  and  the  next  pointer  is  a  pointer to a short int or
133              unsigned short int (rather than int).
134
135       hh     As for h, but the next pointer is a pointer to a signed char  or
136              unsigned char.
137
138       j      As  for h, but the next pointer is a pointer to an intmax_t or a
139              uintmax_t.  This modifier was introduced in C99.
140
141       l      Indicates either that the conversion will be one of d, i, o,  u,
142              x,  X,  or  n and the next pointer is a pointer to a long int or
143              unsigned long int (rather than int), or that the conversion will
144              be one of e, f, or g and the next pointer is a pointer to double
145              (rather than float).  Specifying two l characters is  equivalent
146              to  L.   If  used  with %c or %s, the corresponding parameter is
147              considered as a pointer to a wide  character  or  wide-character
148              string respectively.
149
150       L      Indicates  that the conversion will be either e, f, or g and the
151              next pointer is a pointer to long double or the conversion  will
152              be  d,  i,  o, u, or x and the next pointer is a pointer to long
153              long.
154
155       q      equivalent to L.  This specifier does not exist in ANSI C.
156
157       t      As for h, but the next pointer is  a  pointer  to  a  ptrdiff_t.
158              This modifier was introduced in C99.
159
160       z      As  for  h, but the next pointer is a pointer to a size_t.  This
161              modifier was introduced in C99.
162
163       The following conversion specifiers are available:
164
165       %      Matches a literal '%'.  That is, %% in the format string matches
166              a  single  input '%' character.  No conversion is done (but ini‐
167              tial white space characters are discarded), and assignment  does
168              not occur.
169
170       d      Matches  an  optionally signed decimal integer; the next pointer
171              must be a pointer to int.
172
173       i      Matches an optionally signed integer; the next pointer must be a
174              pointer  to  int.   The  integer is read in base 16 if it begins
175              with 0x or 0X, in base 8 if it begins with 0,  and  in  base  10
176              otherwise.   Only  characters  that  correspond  to the base are
177              used.
178
179       o      Matches an unsigned octal integer; the next pointer  must  be  a
180              pointer to unsigned int.
181
182       u      Matches  an unsigned decimal integer; the next pointer must be a
183              pointer to unsigned int.
184
185       x      Matches an unsigned hexadecimal  integer  (that  may  optionally
186              begin  with  a prefix of 0x or 0X, which is discarded); the next
187              pointer must be a pointer to unsigned int.
188
189       X      Equivalent to x.
190
191       f      Matches an optionally signed  floating-point  number;  the  next
192              pointer must be a pointer to float.
193
194       e      Equivalent to f.
195
196       g      Equivalent to f.
197
198       E      Equivalent to f.
199
200       a      (C99) Equivalent to f.
201
202       s      Matches  a  sequence  of  non-white-space  characters;  the next
203              pointer must be a pointer to the initial element of a  character
204              array  that  is  long  enough to hold the input sequence and the
205              terminating null byte ('\0'), which is added automatically.  The
206              input string stops at white space or at the maximum field width,
207              whichever occurs first.
208
209       c      Matches a sequence of characters whose length  is  specified  by
210              the  maximum field width (default 1); the next pointer must be a
211              pointer to char, and there must be enough room for all the char‐
212              acters  (no  terminating null byte is added).  The usual skip of
213              leading white space is suppressed.  To skip white  space  first,
214              use an explicit space in the format.
215
216       [      Matches a nonempty sequence of characters from the specified set
217              of accepted characters; the next pointer must be  a  pointer  to
218              char,  and  there  must be enough room for all the characters in
219              the string, plus a terminating null byte.   The  usual  skip  of
220              leading  white space is suppressed.  The string is to be made up
221              of characters in (or not  in)  a  particular  set;  the  set  is
222              defined  by  the characters between the open bracket [ character
223              and a close bracket ] character.  The set excludes those charac‐
224              ters  if the first character after the open bracket is a circum‐
225              flex (^).  To include a close bracket in the set,  make  it  the
226              first  character  after  the open bracket or the circumflex; any
227              other position will end the set.  The hyphen character - is also
228              special;  when  placed between two other characters, it adds all
229              intervening characters to the set.  To include a hyphen, make it
230              the   last  character  before  the  final  close  bracket.   For
231              instance,  [^]0-9-]  means  the  set  "everything  except  close
232              bracket,  zero  through nine, and hyphen".  The string ends with
233              the appearance of a character not in the (or, with a circumflex,
234              in) set or when the field width runs out.
235
236       p      Matches  a  pointer  value  (as printed by %p in printf(3)); the
237              next pointer must be a pointer to a pointer to void.
238
239       n      Nothing is expected; instead, the number of characters  consumed
240              thus  far  from  the  input  is stored through the next pointer,
241              which must be a pointer to int.  This is not  a  conversion  and
242              does  not  increase  the  count  returned  by the function.  The
243              assignment can be suppressed with the  *  assignment-suppression
244              character,  but  the  effect  on  the return value is undefined.
245              Therefore %*n conversions should not be used.
246

RETURN VALUE

248       On success, these functions return the number of input  items  success‐
249       fully  matched  and  assigned;  this can be fewer than provided for, or
250       even zero, in the event of an early matching failure.
251
252       The value EOF is returned if the end of input is reached before  either
253       the  first  successful conversion or a matching failure occurs.  EOF is
254       also returned if a read error occurs, in which case the error indicator
255       for the stream (see ferror(3)) is set, and errno is set to indicate the
256       error.
257

ERRORS

259       EAGAIN The file descriptor underlying stream is marked nonblocking, and
260              the read operation would block.
261
262       EBADF  The  file  descriptor  underlying stream is invalid, or not open
263              for reading.
264
265       EILSEQ Input byte sequence does not form a valid character.
266
267       EINTR  The read operation was interrupted by a signal; see signal(7).
268
269       EINVAL Not enough arguments; or format is NULL.
270
271       ENOMEM Out of memory.
272
273       ERANGE The result of an integer conversion would exceed the  size  that
274              can be stored in the corresponding integer type.
275

ATTRIBUTES

277       For   an   explanation   of   the  terms  used  in  this  section,  see
278       attributes(7).
279
280       ┌─────────────────────┬───────────────┬────────────────┐
281Interface            Attribute     Value          
282       ├─────────────────────┼───────────────┼────────────────┤
283scanf(), fscanf(),   │ Thread safety │ MT-Safe locale │
284sscanf(), vscanf(),  │               │                │
285vsscanf(), vfscanf() │               │                │
286       └─────────────────────┴───────────────┴────────────────┘
287

CONFORMING TO

289       The functions fscanf(), scanf(), and sscanf() conform to  C89  and  C99
290       and POSIX.1-2001.  These standards do not specify the ERANGE error.
291
292       The  q  specifier is the 4.4BSD notation for long long, while ll or the
293       usage of L in integer conversions is the GNU notation.
294
295       The Linux version of these functions is based on the GNU libio library.
296       Take  a  look  at the info documentation of GNU libc (glibc-1.08) for a
297       more concise description.
298

NOTES

300   The 'a' assignment-allocation modifier
301       Originally, the GNU C library supported dynamic allocation  for  string
302       inputs (as a nonstandard extension) via the a character.  (This feature
303       is present at least as far back as glibc 2.0.)  Thus, one  could  write
304       the  following  to  have scanf() allocate a buffer for an input string,
305       with a pointer to that buffer being returned in *buf:
306
307           char *buf;
308           scanf("%as", &buf);
309
310       The use of the letter a for this purpose was problematic,  since  a  is
311       also specified by the ISO C standard as a synonym for f (floating-point
312       input).  POSIX.1-2008 instead specifies the m modifier  for  assignment
313       allocation (as documented in DESCRIPTION, above).
314
315       Note  that  the  a modifier is not available if the program is compiled
316       with gcc -std=c99 or gcc -D_ISOC99_SOURCE (unless _GNU_SOURCE  is  also
317       specified),  in  which  case  the  a  is interpreted as a specifier for
318       floating-point numbers (see above).
319
320       Support for the m modifier was added to  glibc  starting  with  version
321       2.7, and new programs should use that modifier instead of a.
322
323       As  well as being standardized by POSIX, the m modifier has the follow‐
324       ing further advantages over the use of a:
325
326       * It may also be applied to %c conversion specifiers (e.g., %3mc).
327
328       * It avoids ambiguity with respect to the %a floating-point  conversion
329         specifier (and is unaffected by gcc -std=c99 etc.).
330

BUGS

332       All  functions  are  fully  C89  conformant, but provide the additional
333       specifiers q and a as well as an additional behavior of  the  L  and  l
334       specifiers.   The  latter  may be considered to be a bug, as it changes
335       the behavior of specifiers defined in C89.
336
337       Some combinations of  the  type  modifiers  and  conversion  specifiers
338       defined by ANSI C do not make sense (e.g., %Ld).  While they may have a
339       well-defined behavior on Linux, this need not to be so on other  archi‐
340       tectures.  Therefore it usually is better to use modifiers that are not
341       defined by ANSI C at all, that is, use q instead of  L  in  combination
342       with d, i, o, u, x, and X conversions or ll.
343
344       The usage of q is not the same as on 4.4BSD, as it may be used in float
345       conversions equivalently to L.
346

EXAMPLES

348       To use the dynamic allocation conversion  specifier,  specify  m  as  a
349       length  modifier  (thus %ms or %m[range]).  The caller must free(3) the
350       returned string, as in the following example:
351
352           char *p;
353           int n;
354
355           errno = 0;
356           n = scanf("%m[a-z]", &p);
357           if (n == 1) {
358               printf("read: %s\n", p);
359               free(p);
360           } else if (errno != 0) {
361               perror("scanf");
362           } else {
363               fprintf(stderr, "No matching characters\n");
364           }
365
366       As shown in the above example, it is necessary to call free(3) only  if
367       the scanf() call successfully read a string.
368

SEE ALSO

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

COLOPHON

373       This  page  is  part of release 5.07 of the Linux man-pages project.  A
374       description of the project, information about reporting bugs,  and  the
375       latest     version     of     this    page,    can    be    found    at
376       https://www.kernel.org/doc/man-pages/.
377
378
379
380GNU                               2020-04-11                          SCANF(3)
Impressum