FSCANF(3P)
FSCANF(3P) β POSIX Programmer's Manual π
β¨ PROLOG β¨
okay so bestie, this manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. π lowkey important, don't skip.
π NAME π
fscanf, scanf, sscanf β convert formatted input β¨ periodt.
π SYNOPSIS π
#include <stdio.h>
int fscanf(FILE *restrict stream, const char *restrict format, ...);
int scanf(const char *restrict format, ...);
int sscanf(const char *restrict s, const char *restrict format, ...);
π¦ DESCRIPTION π¦
The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1β2017 defers to the ISO C standard. π so like, ISO C is the blueprint, no drama.
The fscanf() function shall read from the named input stream. The scanf() function shall read from the standard input stream stdin. The sscanf() function shall read from the string s. Each function reads bytes, interprets them according to a format, and stores the results in its arguments. Each expects, as arguments, a control string format described below, and a set of pointer arguments indicating where the converted input should be stored. The result is undefined if there are insufficient arguments for the format. If the format is exhausted while arguments remain, the excess arguments shall be evaluated but otherwise ignored. π«Ά so basically, feed it a format and pointers, and it does the thing.
Conversions can be applied to the nth argument after the format in the argument list, rather than to the next unused argument. In this case, the conversion specifier character % (see below) is replaced by the sequence "%n$", where n is a decimal integer in the range [1,{NL_ARGMAX}]. This feature provides for the definition of format strings that select arguments in an order appropriate to specific languages. In format strings containing the "%n$" form of conversion specifications, it is unspecified whether numbered arguments in the argument list can be referenced from the format string more than once. π iconic for localization, iykyk.
The format can contain either form of a conversion specificationβthat is, % or "%n$"βbut the two forms cannot be mixed within a single format string. The only exception to this is that %% or %* can be mixed with the "%n$" form. When numbered argument specifications are used, specifying the Nth argument requires that all the leading arguments, from the first to the (N-1)th, are pointers. π¨ no mixing, bestie, it's giving strict.
The fscanf() function in all its forms shall allow detection of a language-dependent radix character in the input string. The radix character is defined in the current locale (category LC_NUMERIC). In the POSIX locale, or in a locale where the radix character is not defined, the radix character shall default to a <period> ('.'). π locale vibes.
The format is a character string, beginning and ending in its initial shift state, if any, composed of zero or more directives. Each directive is composed of one of the following: one or more white-space characters (<space>, <tab>, <newline>, <vertical-tab>, or <form-feed>); an ordinary character (neither % nor a white-space character); or a conversion specification. Each conversion specification is introduced by the character % or the character sequence "%n$", after which the following appear in sequence:
- An optional assignment-suppressing character
'*'. π - An optional non-zero decimal integer that specifies the maximum field width. π
- An optional assignment-allocation character
'm'. π§ - An option length modifier that specifies the size of the receiving object. π
- A conversion specifier character that specifies the type of conversion to be applied. The valid conversion specifiers are described below. β¨
The fscanf() functions shall execute each directive of the format in turn. If a directive fails, as detailed below, the function shall return. Failures are described as input failures (due to the unavailability of input bytes) or matching failures (due to inappropriate input). π two failure flavors, got it.
A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread. β¨
A directive that is an ordinary character shall be executed as follows: the next byte shall be read from the input and compared with the byte that comprises the directive; if the comparison shows that they are not equivalent, the directive shall fail, and the differing and subsequent bytes shall remain unread. Similarly, if end-of-file, an encoding error, or a read error prevents a character from being read, the directive shall fail. π no match, no mercy.
A directive that is a conversion specification defines a set of matching input sequences, as described below for each conversion character. A conversion specification shall be executed in the following steps. πͺ
Input white-space characters (as specified by isspace()) shall be skipped, unless the conversion specification includes a [, c, C, or n conversion specifier. π exceptions exist.
An item shall be read from the input, unless the conversion specification includes an n conversion specifier. An input item shall be defined as the longest sequence of input bytes (up to any specified maximum field width, which may be measured in characters or bytes dependent on the conversion specifier) which is an initial subsequence of a matching sequence. The first byte, if any, after the input item shall remain unread. If the length of the input item is 0, the execution of the conversion specification shall fail; this condition is a matching failure, unless end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure. π₯ longest sequence, periodt.
Except in the case of a % conversion specifier, the input item (or, in the case of a %n conversion specification, the count of input bytes) shall be converted to a type appropriate to the conversion character. If the input item is not a matching sequence, the execution of the conversion specification fails; this condition is a matching failure. Unless assignment suppression was indicated by a '*', the result of the conversion shall be placed in the object pointed to by the first argument following the format argument that has not already received a conversion result if the conversion specification is introduced by %, or in the *n*th argument if introduced by the character sequence "%n$". If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the space provided, the behavior is undefined. β οΈ type matters, no cap.
The %c, %s, and %[ conversion specifiers shall accept an optional assignment-allocation character 'm', which shall cause a memory buffer to be allocated to hold the string converted including a terminating null character. In such a case, the argument corresponding to the conversion specifier should be a reference to a pointer variable that will receive a pointer to the allocated buffer. The system shall allocate a buffer as if malloc() had been called. The application shall be responsible for freeing the memory after usage. If there is insufficient memory to allocate a buffer, the function shall set errno to [ENOMEM] and a conversion error shall result. If the function returns EOF, any memory successfully allocated for parameters using assignment-allocation character 'm' by this call shall be freed before the function returns. π§ malloc energy, but you gotta free it, bestie.
The length modifiers and their meanings π
hhβ Specifies that a followingd,i,o,u,x,X, ornconversion specifier applies to an argument with type pointer tosigned charorunsigned char. π±hβ Specifies that a followingd,i,o,u,x,X, ornconversion specifier applies to an argument with type pointer toshortorunsigned short. πΏl(ell) β Specifies that a followingd,i,o,u,x,X, ornconversion specifier applies to an argument with type pointer tolongorunsigned long; that a followinga,A,e,E,f,F,g, orGconversion specifier applies to an argument with type pointer todouble; or that a followingc,s, or[conversion specifier applies to an argument with type pointer towchar_t. If the'm'assignment-allocation character is specified, the conversion applies to an argument with the type pointer to a pointer towchar_t. πll(ell-ell) β Specifies that a followingd,i,o,u,x,X, ornconversion specifier applies to an argument with type pointer tolong longorunsigned long long. π₯jβ Specifies that a followingd,i,o,u,x,X, ornconversion specifier applies to an argument with type pointer tointmax_toruintmax_t. πzβ Specifies that a followingd,i,o,u,x,X, ornconversion specifier applies to an argument with type pointer tosize_tor the corresponding signed integer type. β¨tβ Specifies that a followingd,i,o,u,x,X, ornconversion specifier applies to an argument with type pointer toptrdiff_tor the corresponding unsigned type. π¦Lβ Specifies that a followinga,A,e,E,f,F,g, orGconversion specifier applies to an argument with type pointer tolong double. π
If a length modifier appears with any conversion specifier other than as specified above, the behavior is undefined. π
The following conversion specifiers are valid π
dβ Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence ofstrtol()with the value10for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer toint. π’iβ Matches an optionally signed integer, whose format is the same as expected for the subject sequence ofstrtol()with0for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer toint. πoβ Matches an optionally signed octal integer, whose format is the same as expected for the subject sequence ofstrtoul()with the value8for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer tounsigned. πuβ Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence ofstrtoul()with the value10for the base argument. In the absence of a size modifier, the application shall ensure that the corresponding argument is a pointer tounsigned. πxβ Matches an optionally signed hexadecimal integer, and its format is exactly what you'd expect for the subject sequence ofstrtoul()when you pass16as thebaseargument. No size modifier? Then the application shall ensure the corresponding argument is a pointer tounsigned. πa,e,f,gβ Matches an optionally signed floating-point number, infinity, or NaN, with the same format as the subject sequence ofstrtod(). No size modifier? The application shall ensure the corresponding argument is a pointer tofloat. π¦- If the
fprintf()family of functions generates character string representations for infinity and NaN (a symbolic entity encoded in floating-point format) to supportIEEE Std 754β1985, then thefscanf()family of functions shall recognize them as input. fr fr.
- If the
sβ Matches a sequence of bytes that are not white-space characters. β¨- If the
'm'assignment-allocation character is not specified, the application shall ensure that the corresponding argument is a pointer to the initial byte of an array ofchar,signed char, orunsigned charlarge enough to accept the sequence and a terminating null character code, which shall be added automatically. Otherwise, the application shall ensure that the corresponding argument is a pointer to a pointer to achar. - If an
l(ell) qualifier is present, the input is a sequence of characters that begins in the initial shift state. Each character shall be converted to a wide character as if by a call to thembrtowc()function, with the conversion state described by anmbstate_tobject initialized to zero before the first character is converted. If the'm'assignment-allocation character is not specified, the application shall ensure that the corresponding argument is a pointer to an array ofwchar_tlarge enough to accept the sequence and the terminating null wide character, which shall be added automatically. Otherwise, the application shall ensure that the corresponding argument is a pointer to a pointer to awchar_t. the way that this handles wide chars? iconic.
- If the
[β Matches a non-empty sequence of bytes from a set of expected bytes (the scanset). The normal skip over white-space characters shall be suppressed in this case. periodt.- If the
'm'assignment-allocation character is not specified, the application shall ensure that the corresponding argument is a pointer to the initial byte of an array ofchar,signed char, orunsigned charlarge enough to accept the sequence and a terminating null byte, which shall be added automatically. Otherwise, the application shall ensure that the corresponding argument is a pointer to a pointer to achar. - If an
l(ell) qualifier is present, the input is a sequence of characters that begins in the initial shift state. Each character in the sequence shall be converted to a wide character as if by a call to thembrtowc()function, with the conversion state described by anmbstate_tobject initialized to zero before the first character is converted. If the'm'assignment-allocation character is not specified, the application shall ensure that the corresponding argument is a pointer to an array ofwchar_tlarge enough to accept the sequence and the terminating null wide character, which shall be added automatically. Otherwise, the application shall ensure that the corresponding argument is a pointer to a pointer to awchar_t. - The conversion specification includes all subsequent bytes in the format string up to and including the matching
<right-square-bracket>(]). The bytes between the square brackets (the scanlist) comprise the scanset, unless the byte after the<left-square-bracket>is a<circumflex>(^), in which case the scanset contains all bytes that do not appear in the scanlist between the<circumflex>and the<right-square-bracket>. If the conversion specification begins with[]or[^], the<right-square-bracket>is included in the scanlist and the next<right-square-bracket>is the matching<right-square-bracket>that ends the conversion specification; otherwise, the first<right-square-bracket>is the one that ends the conversion specification. If a-is in the scanlist and is not the first character, nor the second where the first character is a^, nor the last character, the behavior is implementation-defined. iykyk.
- If the
cβ Matches a sequence of bytes of the number specified by the field width (1if no field width is present in the conversion specification). No null byte is added. The normal skip over white-space characters shall be suppressed in this case. π- If the
'm'assignment-allocation character is not specified, the application shall ensure that the corresponding argument is a pointer to the initial byte of an array ofchar,signed char, orunsigned charlarge enough to accept the sequence. Otherwise, the application shall ensure that the corresponding argument is a pointer to a pointer to achar. - If an
l(ell) qualifier is present, the input shall be a sequence of characters that begins in the initial shift state. Each character in the sequence is converted to a wide character as if by a call to thembrtowc()function, with the conversion state described by anmbstate_tobject initialized to zero before the first character is converted. No null wide character is added. If the'm'assignment-allocation character is not specified, the application shall ensure that the corresponding argument is a pointer to an array ofwchar_tlarge enough to accept the resulting sequence of wide characters. Otherwise, the application shall ensure that the corresponding argument is a pointer to a pointer to awchar_t.
- If the
pβ Matches an implementation-defined set of sequences, which shall be the same as the set of sequences that is produced by the%pconversion specification of the correspondingfprintf()functions. The application shall ensure that the corresponding argument is a pointer to a pointer tovoid. The interpretation of the input item is implementation-defined. If the input item is a value converted earlier during the same program execution, the pointer that results shall compare equal to that value; otherwise, the behavior of the%pconversion specification is undefined. undefined behavior? not cute. πnβ No input is consumed. The application shall ensure that the corresponding argument is a pointer to the integer into which shall be written the number of bytes read from the input so far by this call to thefscanf()functions. Execution of a%nconversion specification shall not increment the assignment count returned at the completion of execution of the function. No argument shall be converted, but one shall be consumed. If the conversion specification includes an assignment-suppressing character or a field width, the behavior is undefined. so don't do that bestie.Cβ Equivalent tolc.Sβ Equivalent tols.%β Matches a single'%'character; no conversion or assignment occurs. The complete conversion specification shall be%%.
If a conversion specification is invalid, the behavior is undefined. π
The conversion specifiers A, E, F, G, and X are also valid and shall be equivalent to a, e, f, g, and x, respectively. slay.
If end-of-file is encountered during input, conversion shall be terminated. If end-of-file occurs before any bytes matching the current conversion specification (except for %n) have been read (other than leading white-space characters, where permitted), execution of the current conversion specification shall terminate with an input failure. Otherwise, unless execution of the current conversion specification is terminated with a matching failure, execution of the following conversion specification (if any) shall be terminated with an input failure.
Reaching the end of the string in sscanf() shall be equivalent to encountering end-of-file for fscanf().
If conversion terminates on a conflicting input, the offending input is left unread in the input. Any trailing white space (including <newline> characters) shall be left unread unless matched by a conversion specification. The success of literal matches and suppressed assignments is only directly determinable via the %n conversion specification. only %n can tell you, no cap.
The fscanf() and scanf() functions may mark the last data access timestamp of the file associated with stream for update. The last data access timestamp shall be marked for update by the first successful execution of fgetc(), fgets(), fread(), getc(), getchar(), getdelim(), getline(), gets(), fscanf(), or scanf() using stream that returns data not supplied by a prior call to ungetc().
β¨ RETURN VALUE β¨
Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure. If the input ends before the first conversion (if any) has completed, and without a matching failure having occurred, EOF shall be returned. If an error occurs before the first conversion (if any) has completed, and without a matching failure having occurred, EOF shall be returned and errno shall be set to indicate the error. If a read error occurs, the error indicator for the stream shall be set. bestie, check that return value.
π₯ ERRORS π₯
For the conditions under which the fscanf() functions fail and may fail, refer to fgetc() or fgetwc().
In addition, the fscanf() function shall fail if:
EILSEQβ Input byte sequence does not form a valid character.ENOMEMβ Insufficient storage space is available.
In addition, the fscanf() function may fail if:
EINVALβ There are insufficient arguments.
The following sections are informative.
π EXAMPLES π
okay bestie, let's actually see this thing do its lil magic, because reading about it is one thing and watching it cook is another π
So you call:
int i, n; float x; char name[50];
n = scanf("%d%f%s", &i, &x, name);
and you feed it this input line:
25 54.32E-1 Hamster
and boom β n gets the value 3, i gets 25, x gets 5.432, and name holds the string "Hamster". like, it literally just ate all three conversions and reported back "yeah that's 3 things, we good" π
Now watch this one, it's giving main character energy:
int i; float x; char name[50];
(void) scanf("%2d%f%*d %[0123456789]", &i, &x, name);
with this input:
56789 0123 56a72
it assigns 56 to i, 789.0 to x, skips 0123, and drops the string "56\0" into name. and then the next call to getchar() shall return the character 'a'. iconic behaviour, no notes π₯
Reading Data into an Array π
This next call uses fscanf() to read three floating-point numbers from standard input straight into the input array:
float input[3]; fscanf (stdin, "%f %f %f", input, input+1, input+2);
look at her. three floats, one line, zero drama β¨
π«Ά APPLICATION USAGE π«Ά
If the application calling fscanf() has any objects of type wint_t or wchar_t, it must also include the <wchar.h> header to have these objects defined. no cap, don't skip this one π
For functions that allocate memory as if by malloc(), the application should release such memory when it is no longer required by a call to free(). For fscanf(), this is memory allocated via use of the 'm' assignment-allocation character. like β you asked for that memory, bestie, so you're the one who's gotta let it go π
π§ RATIONALE π§
This function is aligned with the ISO/IEC 9899:1999 standard, and in doing so a few "obvious" things were not included. Specifically, the set of characters allowed in a scanset is limited to single-byte characters. In other similar places, multi-byte characters have been permitted, but for alignment with the ISO/IEC 9899:1999 standard, it has not been done here. Applications needing this could use the corresponding wide-character functions to achieve the desired results.
so yeah β it's a deliberate choice, not a whoopsie. she's standards-compliant on purpose π
β FUTURE DIRECTIONS β
None.
(yeah that's it. nothing coming. the future is empty. slay, honestly πΈ)
π SEE ALSO π
- Section 2.5, Standard I/O Streams
fprintf()getc()setlocale()strtod()strtol()strtoul()wcrtomb()
The Base Definitions volume of POSIX.1β2017, Chapter 7, Locale, <inttypes.h>, <langinfo.h>, <stdio.h>, <wchar.h>
like, if you wanna go deeper, these are your girls. iykyk π
π COPYRIGHT π
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
and that's the whole page, bestie!! π this one came from IEEE / The Open Group, dated 2017, and it's the FSCANF(3P) page β go forth and scan your floats responsibly πβ¨
π¦ where this page comes from
- alpine 3.22: man-pages-posix 2017a-r0 Β· custom
- alpine 3.23: man-pages-posix 2017a-r0 Β· custom
- alpine 3.24: man-pages-posix 2017a-r0 Β· custom
- arch rolling: man-pages 6.19-1
- 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-posix 2017a
- opensuse-leap 16.0: man-pages-posix 2017a-160000.4.1 Β· SUSE-IEEE
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms