1SCANF(3) Linux Programmer's Manual SCANF(3)
2
3
4
6 scanf, fscanf, sscanf, vscanf, vsscanf, vfscanf - input format conver‐
7 sion
8
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
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 D Equivalent to ld; this exists only for backward compatibility.
174 (Note: thus only in libc4. In libc5 and glibc the %D is
175 silently ignored, causing old programs to fail mysteriously.)
176
177 i Matches an optionally signed integer; the next pointer must be a
178 pointer to int. The integer is read in base 16 if it begins
179 with 0x or 0X, in base 8 if it begins with 0, and in base 10
180 otherwise. Only characters that correspond to the base are
181 used.
182
183 o Matches an unsigned octal integer; the next pointer must be a
184 pointer to unsigned int.
185
186 u Matches an unsigned decimal integer; the next pointer must be a
187 pointer to unsigned int.
188
189 x Matches an unsigned hexadecimal integer; the next pointer must
190 be a pointer to unsigned int.
191
192 X Equivalent to x.
193
194 f Matches an optionally signed floating-point number; the next
195 pointer must be a pointer to float.
196
197 e Equivalent to f.
198
199 g Equivalent to f.
200
201 E Equivalent to f.
202
203 a (C99) Equivalent to f.
204
205 s Matches a sequence of non-white-space characters; the next
206 pointer must be a pointer to the initial element of a character
207 array that is long enough to hold the input sequence and the
208 terminating null byte ('\0'), which is added automatically. The
209 input string stops at white space or at the maximum field width,
210 whichever occurs first.
211
212 c Matches a sequence of characters whose length is specified by
213 the maximum field width (default 1); the next pointer must be a
214 pointer to char, and there must be enough room for all the char‐
215 acters (no terminating null byte is added). The usual skip of
216 leading white space is suppressed. To skip white space first,
217 use an explicit space in the format.
218
219 [ Matches a nonempty sequence of characters from the specified set
220 of accepted characters; the next pointer must be a pointer to
221 char, and there must be enough room for all the characters in
222 the string, plus a terminating null byte. The usual skip of
223 leading white space is suppressed. The string is to be made up
224 of characters in (or not in) a particular set; the set is
225 defined by the characters between the open bracket [ character
226 and a close bracket ] character. The set excludes those charac‐
227 ters if the first character after the open bracket is a circum‐
228 flex (^). To include a close bracket in the set, make it the
229 first character after the open bracket or the circumflex; any
230 other position will end the set. The hyphen character - is also
231 special; when placed between two other characters, it adds all
232 intervening characters to the set. To include a hyphen, make it
233 the last character before the final close bracket. For
234 instance, [^]0-9-] means the set "everything except close
235 bracket, zero through nine, and hyphen". The string ends with
236 the appearance of a character not in the (or, with a circumflex,
237 in) set or when the field width runs out.
238
239 p Matches a pointer value (as printed by %p in printf(3); the next
240 pointer must be a pointer to a pointer to void.
241
242 n Nothing is expected; instead, the number of characters consumed
243 thus far from the input is stored through the next pointer,
244 which must be a pointer to int. This is not a conversion and
245 does not increase the count returned by the function. The
246 assignment can be suppressed with the * assignment-suppression
247 character, but the effect on the return value is undefined.
248 Therefore %*n conversions should not be used.
249
251 On success, these functions return the number of input items success‐
252 fully matched and assigned; this can be fewer than provided for, or
253 even zero, in the event of an early matching failure.
254
255 The value EOF is returned if the end of input is reached before either
256 the first successful conversion or a matching failure occurs. EOF is
257 also returned if a read error occurs, in which case the error indicator
258 for the stream (see ferror(3)) is set, and errno is set to indicate the
259 error.
260
262 EAGAIN The file descriptor underlying stream is marked nonblocking, and
263 the read operation would block.
264
265 EBADF The file descriptor underlying stream is invalid, or not open
266 for reading.
267
268 EILSEQ Input byte sequence does not form a valid character.
269
270 EINTR The read operation was interrupted by a signal; see signal(7).
271
272 EINVAL Not enough arguments; or format is NULL.
273
274 ENOMEM Out of memory.
275
276 ERANGE The result of an integer conversion would exceed the size that
277 can be stored in the corresponding integer type.
278
280 For an explanation of the terms used in this section, see
281 attributes(7).
282
283 ┌─────────────────────┬───────────────┬────────────────┐
284 │Interface │ Attribute │ Value │
285 ├─────────────────────┼───────────────┼────────────────┤
286 │scanf(), fscanf(), │ Thread safety │ MT-Safe locale │
287 │sscanf(), vscanf(), │ │ │
288 │vsscanf(), vfscanf() │ │ │
289 └─────────────────────┴───────────────┴────────────────┘
290
292 The functions fscanf(), scanf(), and sscanf() conform to C89 and C99
293 and POSIX.1-2001. These standards do not specify the ERANGE error.
294
295 The q specifier is the 4.4BSD notation for long long, while ll or the
296 usage of L in integer conversions is the GNU notation.
297
298 The Linux version of these functions is based on the GNU libio library.
299 Take a look at the info documentation of GNU libc (glibc-1.08) for a
300 more concise description.
301
303 The 'a' assignment-allocation modifier
304 Originally, the GNU C library supported dynamic allocation for string
305 inputs (as a nonstandard extension) via the a character. (This feature
306 is present at least as far back as glibc 2.0.) Thus, one could write
307 the following to have scanf() allocate a buffer for an input string,
308 with a pointer to that buffer being returned in *buf:
309
310 char *buf;
311 scanf("%as", &buf);
312
313 The use of the letter a for this purpose was problematic, since a is
314 also specified by the ISO C standard as a synonym for f (floating-point
315 input). POSIX.1-2008 instead specifies the m modifier for assignment
316 allocation (as documented in DESCRIPTION, above).
317
318 Note that the a modifier is not available if the program is compiled
319 with gcc -std=c99 or gcc -D_ISOC99_SOURCE (unless _GNU_SOURCE is also
320 specified), in which case the a is interpreted as a specifier for
321 floating-point numbers (see above).
322
323 Support for the m modifier was added to glibc starting with version
324 2.7, and new programs should use that modifier instead of a.
325
326 As well as being standardized by POSIX, the m modifier has the follow‐
327 ing further advantages over the use of a:
328
329 * It may also be applied to %c conversion specifiers (e.g., %3mc).
330
331 * It avoids ambiguity with respect to the %a floating-point conversion
332 specifier (and is unaffected by gcc -std=c99 etc.).
333
335 All functions are fully C89 conformant, but provide the additional
336 specifiers q and a as well as an additional behavior of the L and l
337 specifiers. The latter may be considered to be a bug, as it changes
338 the behavior of specifiers defined in C89.
339
340 Some combinations of the type modifiers and conversion specifiers
341 defined by ANSI C do not make sense (e.g., %Ld). While they may have a
342 well-defined behavior on Linux, this need not to be so on other archi‐
343 tectures. Therefore it usually is better to use modifiers that are not
344 defined by ANSI C at all, that is, use q instead of L in combination
345 with d, i, o, u, x, and X conversions or ll.
346
347 The usage of q is not the same as on 4.4BSD, as it may be used in float
348 conversions equivalently to L.
349
351 To use the dynamic allocation conversion specifier, specify m as a
352 length modifier (thus %ms or %m[range]). The caller must free(3) the
353 returned string, as in the following example:
354
355 char *p;
356 int n;
357
358 errno = 0;
359 n = scanf("%m[a-z]", &p);
360 if (n == 1) {
361 printf("read: %s\n", p);
362 free(p);
363 } else if (errno != 0) {
364 perror("scanf");
365 } else {
366 fprintf(stderr, "No matching characters\n");
367 }
368
369 As shown in the above example, it is necessary to call free(3) only if
370 the scanf() call successfully read a string.
371
373 getc(3), printf(3), setlocale(3), strtod(3), strtol(3), strtoul(3)
374
376 This page is part of release 4.16 of the Linux man-pages project. A
377 description of the project, information about reporting bugs, and the
378 latest version of this page, can be found at
379 https://www.kernel.org/doc/man-pages/.
380
381
382
383GNU 2017-09-15 SCANF(3)