4.9 INPUT/OUTPUT 4.9.1 Introduction The header declares three types, several macros, and many functions for performing input and output. The types declared are size_t (described in $4.1.5); FILE which is an object type capable of recording all the information needed to control a stream, including its file position indicator, a pointer to its associated buffer, an error indicator that records whether a read/write error has occurred, and an end-of-file indicator that records whether the end of the file has been reached; and fpos_t which is an object type capable of recording all the information needed to specify uniquely every position within a file. The macros are NULL (described in $4.1.5); _IOFBF _IOLBF _IONBF which expand to distinct integral constant expressions, suitable for use as the third argument to the setvbuf function; BUFSIZ which expands to an integral constant expression, which is the size of the buffer used by the setbuf function; EOF which expands to a negative integral constant expression that is returned by several functions to indicate end-of-file ,that is, no more input from a stream; FOPEN_MAX which expands to an integral constant expression that is the minimum number of files that the implementation guarantees can be open simultaneously; FILENAME_MAX which expands to an integral constant expression that is the maximum length for a file name string that the implementation guarantees can be opened; L_tmpnam which expands to an integral constant expression that is the size of an array of char large enough to hold a temporary file name string generated by the tmpnam function; SEEK_CUR SEEK_END SEEK_SET which expand to distinct integral constant expressions, suitable for use as the third argument to the fseek function; TMP_MAX which expands to an integral constant expression that is the minimum number of unique file names that shall be generated by the tmpnam function; stderr stdin stdout which are expressions of type ``pointer to FILE '' that point to the FILE objects associated, respectively, with the standard error, input, and output streams. Forward references: files ($4.9.3), the fseek function ($4.9.9.2), streams ($4.9.2), the tmpnam function ($4.9.4.4). 4.9.2 Streams Input and output, whether to or from physical devices such as terminals and tape drives, or whether to or from files supported on structured storage devices, are mapped into logical data streams ,whose properties are more uniform than their various inputs and outputs. Two forms of mapping are supported, for text streams and for binary streams . A text stream is an ordered sequence of characters composed into lines , each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one-to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printable characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined. A binary stream is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream shall compare equal to the data that were earlier written out to that stream, under the same implementation. Such a stream may, however, have an implementation-defined number of null characters appended. "Environmental limits" An implementation shall support text files with lines containing at least 254 characters, including the terminating new-line character. The value of the macro BUFSIZ shall be at least 256. 4.9.3 Files A stream is associated with an external file (which may be a physical device) by opening a file, which may involve creating a new file. Creating an existing file causes its former contents to be discarded, if necessary, so that it appears as if newly created. If a file can support positioning requests (such as a disk file, as opposed to a terminal), then a file position indicator /100/file pointer .associated with the stream is positioned at the start (character number zero) of the file, unless the file is opened with append mode in which case it is implementation-defined whether the file position indicator is positioned at the beginning or the end of the file. The file position indicator is maintained by subsequent reads, writes, and positioning requests, to facilitate an orderly progression through the file. All input takes place as if characters were read by successive calls to the fgetc function; all output takes place as if characters were written by successive calls to the fputc function. Binary files are not truncated, except as defined in $4.9.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation-defined. When a stream is unbuffered , characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered ,characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered ,characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment. Support for these characteristics is implementation-defined, and may be affected via the setbuf and setvbuf functions. A file may be disassociated from its controlling stream by closing the file. Output streams are flushed (any unwritten buffer contents are transmitted to the host environment) before the stream is disassociated from the file. The value of a pointer to a FILE object is indeterminate after the associated file is closed (including the standard text streams). Whether a file of zero length (on which no characters have been written by an output stream) actually exists is implementation-defined. The file may be subsequently reopened, by the same or another program execution, and its contents reclaimed or modified (if it can be repositioned at its start). If the main function returns to its original caller, or if the exit function is called, all open files are closed (hence all output streams are flushed) before program termination. Other paths to program termination, such as calling the abort function, need not close all files properly. The address of the FILE object used to control a stream may be significant; a copy of a FILE object may not necessarily serve in place of the original. At program startup, three text streams are predefined and need not be opened explicitly --- standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). When opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device. Functions that open additional (nontemporary) files require a file name ,which is a string. The rules for composing valid file names are implementation-defined. Whether the same file can be simultaneously open multiple times is also implementation-defined. "Environmental limits" The value of the macro FOPEN_MAX shall be at least eight, including the three standard text streams. Forward references: the exit function ($4.10.4.3), the fgetc function ($4.9.7.1), the fopen function ($4.9.5.3), the fputc function ($4.9.7.3), the setbuf function ($4.9.5.5), the setvbuf function ($4.9.5.6). 4.9.4 Operations on files 4.9.4.1 The remove function Synopsis #include int remove(const char *filename); Description The remove function causes the file whose name is the string pointed to by filename to be no longer accessible by that name. A subsequent attempt to open that file using that name will fail, unless it is created anew. If the file is open, the behavior of the remove function is implementation-defined. Returns The remove function returns zero if the operation succeeds, nonzero if it fails. 4.9.4.2 The rename function Synopsis #include int rename(const char *old, const char *new); Description The rename function causes the file whose name is the string pointed to by old to be henceforth known by the name given by the string pointed to by new . The file named old is effectively removed. If a file named by the string pointed to by new exists prior to the call to the rename function, the behavior is implementation-defined. Returns The rename function returns zero if the operation succeeds, nonzero if it fails, in which case if the file existed previously it is still known by its original name. 4.9.4.3 The tmpfile function Synopsis #include FILE *tmpfile(void); Description The tmpfile function creates a temporary binary file that will automatically be removed when it is closed or at program termination. If the program terminates abnormally, whether an open temporary file is removed is implementation-defined. The file is opened for update with wb+ mode. Returns The tmpfile function returns a pointer to the stream of the file that it created. If the file cannot be created, the tmpfile function returns a null pointer. Forward references: the fopen function ($4.9.5.3). 4.9.4.4 The tmpnam function Synopsis #include char *tmpnam(char *s); Description The tmpnam function generates a string that is a valid file name and that is not the same as the name of an existing file./102/ The tmpnam function generates a different string each time it is called, up to TMP_MAX times. If it is called more than TMP_MAX times, the behavior is implementation-defined. The implementation shall behave as if no library function calls the tmpnam function. Returns If the argument is a null pointer, the tmpnam function leaves its result in an internal static object and returns a pointer to that object. Subsequent calls to the tmpnam function may modify the same object. If the argument is not a null pointer, it is assumed to point to an array of at least L_tmpnam char s; the tmpnam function writes its result in that array and returns the argument as its value. "Environmental limits" The value of the macro TMP_MAX shall be at least 25. 4.9.5 File access functions 4.9.5.1 The fclose function Synopsis #include int fclose(FILE *stream); Description The fclose function causes the stream pointed to by stream to be flushed and the associated file to be closed. Any unwritten buffered data for the stream are delivered to the host environment to be written to the file; any unread buffered data are discarded. The stream is disassociated from the file. If the associated buffer was automatically allocated, it is deallocated. Returns The fclose function returns zero if the stream was successfully closed, or EOF if any errors were detected. 4.9.5.2 The fflush function Synopsis #include int fflush(FILE *stream); Description If stream points to an output stream or an update stream in which the most recent operation was output, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined. If stream is a null pointer, the fflush function performs this flushing action on all streams for which the behavior is defined above. Returns The fflush function returns EOF if a write error occurs, otherwise zero. Forward references: the ungetc function ($4.9.7.11). 4.9.5.3 The fopen function Synopsis #include FILE *fopen(const char *filename, const char *mode); Description The fopen function opens the file whose name is the string pointed to by filename , and associates a stream with it. The argument mode points to a string beginning with one of the following sequences:/103/ "r" open text file for reading "w" truncate to zero length or create text file for writing "a" append; open or create text file for writing at end-of-file "rb" open binary file for reading "wb" truncate to zero length or create binary file for writing "ab" append; open or create binary file for writing at end-of-file "r+" open text file for update (reading and writing) "w+" truncate to zero length or create text file for update "a+" append; open or create text file for update, writing at end-of-file "r+b" or "rb+" open binary file for update (reading and writing) "w+b" or "wb+" truncate to zero length or create binary file for update "a+b" or "ab+" append; open or create binary file for update, writing at end-of-file Opening a file with read mode ('r' as the first character in the mode argument) fails if the file does not exist or cannot be read. Opening a file with append mode ('a' as the first character in the mode argument) causes all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to the fseek function. In some implementations, opening a binary file with append mode ('b' as the second or third character in the mode argument) may initially position the file position indicator for the stream beyond the last data written, because of null character padding. When a file is opened with update mode ('+' as the second or third character in the mode argument), both input and output may be performed on the associated stream. However, output may not be directly followed by input without an intervening call to the fflush function or to a file positioning function ( fseek , fsetpos , or rewind ), and input may not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file. Opening a file with update mode may open or create a binary stream in some implementations. When opened, a stream is fully buffered if and only if it can be determined not to refer to an interactive device. The error and end-of-file indicators for the stream are cleared. Returns The fopen function returns a pointer to the object controlling the stream. If the open operation fails, fopen returns a null pointer. Forward references: file positioning functions ($4.9.9). 4.9.5.4 The freopen function Synopsis #include FILE *freopen(const char *filename, const char *mode, FILE *stream); Description The freopen function opens the file whose name is the string pointed to by filename and associates the stream pointed to by stream with it. The mode argument is used just as in the fopen function. The freopen function first attempts to close any file that is associated with the specified stream. Failure to close the file successfully is ignored. The error and end-of-file indicators for the stream are cleared. Returns The freopen function returns a null pointer if the open operation fails. Otherwise, freopen returns the value of stream . 4.9.5.5 The setbuf function Synopsis #include void setbuf(FILE *stream, char *buf); Description Except that it returns no value, the setbuf function is equivalent to the setvbuf function invoked with the values _IOFBF for mode and BUFSIZ for size , or (if buf is a null pointer), with the value _IONBF for mode . Returns The setbuf function returns no value. Forward references: the setvbuf function ($4.9.5.6). 4.9.5.6 The setvbuf function Synopsis #include int setvbuf(FILE *stream, char *buf, int mode, size_t size); Description The setvbuf function may be used after the stream pointed to by stream has been associated with an open file but before any other operation is performed on the stream. The argument mode determines how stream will be buffered, as follows: _IOFBF causes input/output to be fully buffered; _IOLBF causes output to be line buffered; _IONBF causes input/output to be unbuffered. If buf is not a null pointer, the array it points to may be used instead of a buffer allocated by the setvbuf function./105/ The argument size specifies the size of the array. The contents of the array at any time are indeterminate. Returns The setvbuf function returns zero on success, or nonzero if an invalid value is given for mode or if the request cannot be honored. 4.9.6 Formatted input/output functions 4.9.6.1 The fprintf function Synopsis #include int fprintf(FILE *stream, const char *format, ...); Description The fprintf function writes output to the stream pointed to by stream , under control of the string pointed to by format that specifies how subsequent arguments are converted for output. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. The fprintf function returns when the end of the format string is encountered. The format shall be a multibyte character sequence, beginning and ending in its initial shift state. The format is composed of zero or more directives: ordinary multibyte characters (not % ), which are copied unchanged to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent arguments. Each conversion specification is introduced by the character % . After the % , the following appear in sequence: * Zero or more flags that modify the meaning of the conversion specification. * An optional decimal integer specifying a minimum field width ./106/ If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left adjustment flag, described later, has been given) to the field width. * An optional precision that gives the minimum number of digits to appear for the d , i , o , u , x , and X conversions, the number of digits to appear after the decimal-point character for e , E , and f conversions, the maximum number of significant digits for the g and G conversions, or the maximum number of characters to be written from a string in s conversion. The precision takes the form of a period ( . ) followed by an optional decimal integer; if the integer is omitted, it is treated as zero. * An optional h specifying that a following d , i , o , u , x , or X conversion specifier applies to a short int or unsigned short int argument (the argument will have been promoted according to the integral promotions, and its value shall be converted to short int or unsigned short int before printing); an optional h specifying that a following n conversion specifier applies to a pointer to a short int argument; an optional l (ell) specifying that a following d , i , o , u , x , or X conversion specifier applies to a long int or unsigned long int argument; an optional l specifying that a following n conversion specifier applies to a pointer to a long int argument; or an optional L specifying that a following e , E , f , g , or G conversion specifier applies to a long double argument. If an h , l , or L appears with any other conversion specifier, the behavior is undefined. * A character that specifies the type of conversion to be applied. A field width or precision, or both, may be indicated by an asterisk * instead of a digit string. In this case, an int argument supplies the field width or precision. The arguments specifying field width or precision, or both, shall appear (in that order) before the argument (if any) to be converted. A negative field width argument is taken as a - flag followed by a positive field width. A negative precision argument is taken as if it were missing. The flag characters and their meanings are The result of the conversion will be left-justified within the field. The result of a signed conversion will always begin with a plus or minus sign. If the first character of a signed conversion is not a sign, or if a signed conversion results in no characters, a space will be prepended to the result. If the space and + flags both appear, the space flag will be ignored. The result is to be converted to an ``alternate form.'' For o conversion, it increases the precision to force the first digit of the result to be a zero. For x (or X ) conversion, a nonzero result will have 0x (or 0X ) prepended to it. For e , E , f , g , and G conversions, the result will always contain a decimal-point character, even if no digits follow it (normally, a decimal-point character appears in the result of these conversions only if a digit follows it). For g and G conversions, trailing zeros will not be removed from the result. For other conversions, the behavior is undefined. For d , i , o , u , x , X , e , E , f , g , and G conversions, leading zeros (following any indication of sign or base) are used to pad to the field width; no space padding is performed. If the 0 and - flags both appear, the 0 flag will be ignored. For d , i , o , u , x , and X conversions, if a precision is specified, the 0 flag will be ignored. For other conversions, the behavior is undefined. The conversion specifiers and their meanings are The int argument is converted to signed decimal ( d or i ), unsigned octal ( o ), unsigned decimal ( u ), or unsigned hexadecimal notation ( x or X ); the letters abcdef are used for x conversion and the letters ABCDEF for X conversion. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it will be expanded with leading zeros. The default precision is 1. The result of converting a zero value with an explicit precision of zero is no characters. The double argument is converted to decimal notation in the style [-]ddd.ddd , where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal-point character appears, at least one digit appears before it. The value is rounded to the appropriate number of digits. The double argument is converted in the style [-]d.ddde+- dd , where there is one digit before the decimal-point character (which is nonzero if the argument is nonzero) and the number of digits after it is equal to the precision; if the precision is missing, it is taken as 6; if the precision is zero, no decimal-point character appears. The value is rounded to the appropriate number of digits. The E conversion specifier will produce a number with E instead of e introducing the exponent. The exponent always contains at least two digits. If the value is zero, the exponent is zero. The double argument is converted in style f or e (or in style E in the case of a G conversion specifier), with the precision specifying the number of significant digits. If an explicit precision is zero, it is taken as 1. The style used depends on the value converted; style e will be used only if the exponent resulting from such a conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional portion of the result; a decimal-point character appears only if it is followed by a digit. The int argument is converted to an unsigned char , and the resulting character is written. The argument shall be a pointer to an array of character type./107/ Characters from the array are written up to (but not including) a terminating null character; if the precision is specified, no more than that many characters are written. If the precision is not specified or is greater than the size of the array, the array shall contain a null character. The argument shall be a pointer to void . The value of the pointer is converted to a sequence of printable characters, in an implementation-defined manner. The argument shall be a pointer to an integer into which is written the number of characters written to the output stream so far by this call to fprintf . No argument is converted. A % is written. No argument is converted. The complete conversion specification shall be %% . If a conversion specification is invalid, the behavior is undefined. If any argument is, or points to, a union or an aggregate (except for an array of character type using %s conversion, or a pointer cast to be a pointer to void using %p conversion), the behavior is undefined. In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result. Returns The fprintf function returns the number of characters transmitted, or a negative value if an output error occurred. "Environmental limit" The minimum value for the maximum number of characters produced by any single conversion shall be 509. Examples To print a date and time in the form ``Sunday, July 3, 10:02,'' where weekday and month are pointers to strings: #include fprintf(stdout, "%s, %s %d, %.2d:%.2d\n", weekday, month, day, hour, min); To print PI to five decimal places: #include #include fprintf(stdout, "pi = %.5f\n", 4 * atan(1.0)); 4.9.6.2 The fscanf function Synopsis #include int fscanf(FILE *stream, const char *format, ...); Description The fscanf function reads input from the stream pointed to by stream , under control of the string pointed to by format that specifies the admissible input sequences and how they are to be converted for assignment, using subsequent arguments as pointers to the objects to receive the converted input. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. The format shall be a multibyte character sequence, beginning and ending in its initial shift state. The format is composed of zero or more directives: one or more white-space characters; an ordinary multibyte character (not % ); or a conversion specification. Each conversion specification is introduced by the character % . After the % , the following appear in sequence: * An optional assignment-suppressing character * . * An optional decimal integer that specifies the maximum field width. * An optional h , l (ell) or L indicating the size of the receiving object. The conversion specifiers d , i , and n shall be preceded by h if the corresponding argument is a pointer to short int rather than a pointer to int , or by l if it is a pointer to long int . Similarly, the conversion specifiers o , u , and x shall be preceded by h if the corresponding argument is a pointer to unsigned short int rather than a pointer to unsigned int , or by l if it is a pointer to unsigned long int . Finally, the conversion specifiers e , f , and g shall be preceded by l if the corresponding argument is a pointer to double rather than a pointer to float , or by L if it is a pointer to long double . If an h , l , or L appears with any other conversion specifier, the behavior is undefined. * A character that specifies the type of conversion to be applied. The valid conversion specifiers are described below. The fscanf function executes each directive of the format in turn. If a directive fails, as detailed below, the fscanf function returns. Failures are described as input failures (due to the unavailability of input characters), or matching failures (due to inappropriate input). A directive composed of white space is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. A directive that is an ordinary multibyte character is executed by reading the next characters of the stream. If one of the characters differs from one comprising the directive, the directive fails, and the differing and subsequent characters remain unread. A directive that is a conversion specification defines a set of matching input sequences, as described below for each specifier. A conversion specification is executed in the following steps: Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [ , c , or n specifier. An input item is read from the stream, unless the specification includes an n specifier. An input item is defined as the longest sequence of input characters (up to any specified maximum field width) which is an initial subsequence of a matching sequence. The first character, if any, after the input item remains unread. If the length of the input item is zero, the execution of the directive fails: this condition is a matching failure, unless an error prevented input from the stream, in which case it is an input failure. Except in the case of a % specifier, the input item (or, in the case of a %n directive, the count of input characters) is converted to a type appropriate to the conversion specifier. If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure. Unless assignment suppression was indicated by a * , the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. 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. The following conversion specifiers are valid: Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument shall be a pointer to integer. Matches an optionally signed integer, whose format is the same as expected for the subject sequence of the strtol function with the value 0 for the base argument. The corresponding argument shall be a pointer to integer. Matches an optionally signed octal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 8 for the base argument. The corresponding argument shall be a pointer to unsigned integer. Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 10 for the base argument. The corresponding argument shall be a pointer to unsigned integer. Matches an optionally signed hexadecimal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 16 for the base argument. The corresponding argument shall be a pointer to unsigned integer. Matches an optionally signed floating-point number, whose format is the same as expected for the subject string of the strtod function. The corresponding argument shall be a pointer to floating. Matches a sequence of non-white-space characters.rN The corresponding argument shall be a pointer to the initial character of an array large enough to accept the sequence and a terminating null character, which will be added automatically. Matches a nonempty sequence of charactersrN from a set of expected characters (the scanset ). The corresponding argument shall be a pointer to the initial character of an array large enough to accept the sequence and a terminating null character, which will be added automatically. The conversion specifier includes all subsequent characters in the format string, up to and including the matching right bracket ( ] ). The characters between the brackets (the scanlist ) comprise the scanset, unless the character after the left bracket is a circumflex ( ^ ), in which case the scanset contains all characters that do not appear in the scanlist between the circumflex and the right bracket. As a special case, if the conversion specifier begins with [] or [^] , the right bracket character is in the scanlist and the next right bracket character is the matching right bracket that ends the specification. If a - character is in the scanlist and is not the first, nor the second where the first character is a ^ , nor the last character, the behavior is implementation-defined. Matches a sequence of charactersrN of the number specified by the field width (1 if no field width is present in the directive). The corresponding argument shall be a pointer to the initial character of an array large enough to accept the sequence. No null character is added. Matches an implementation-defined set of sequences, which should be the same as the set of sequences that may be produced by the %p conversion of the fprintf function. The corresponding argument shall be a pointer to a pointer to void . The interpretation of the input item is implementation-defined; however, for any input item other than a value converted earlier during the same program execution, the behavior of the %p conversion is undefined. No input is consumed. The corresponding argument shall be a pointer to integer into which is to be written the number of characters read from the input stream so far by this call to the fscanf function. Execution of a %n directive does not increment the assignment count returned at the completion of execution of the fscanf function. Matches a single % ; no conversion or assignment occurs. The complete conversion specification shall be %% . If a conversion specification is invalid, the behavior is undefined./110/ The conversion specifiers E , G , and X are also valid and behave the same as, respectively, e , g , and x . If end-of-file is encountered during input, conversion is terminated. If end-of-file occurs before any characters matching the current directive have been read (other than leading white space, where permitted), execution of the current directive terminates with an input failure; otherwise, unless execution of the current directive is terminated with a matching failure, execution of the following directive (if any) is terminated with an input failure. If conversion terminates on a conflicting input character, the offending input character is left unread in the input stream. Trailing white space (including new-line characters) is left unread unless matched by a directive. The success of literal matches and suppressed assignments is not directly determinable other than via the %n directive. Returns The fscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the fscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure. Examples The call: #include int n, i; float x; char name[50]; n = fscanf(stdin, "%d%f%s", &i, &x, name); with the input line: 25 54.32E-1 thompson will assign to n the value 3, to i the value 25, to x the value 5.432, and name will contain thompson\0 . Or: #include int i; float x; char name[50]; fscanf(stdin, "%2d%f%*d %[0123456789]", &i, &x, name); with input: 56789 0123 56a72 will assign to i the value 56 and to x the value 789.0, will skip 0123, and name will contain 56\0 . The next character read from the input stream will be a . To accept repeatedly from stdin a quantity, a unit of measure and an item name: #include int count; float quant; char units[21], item[21]; while (!feof(stdin) && !ferror(stdin)) { count = fscanf(stdin, "%f%20s of %20s", &quant, units, item); fscanf(stdin,"%*[^\n]"); } If the stdin stream contains the following lines: 2 quarts of oil -12.8degrees Celsius lots of luck 10.0LBS of fertilizer 100ergs of energy the execution of the above example will be equivalent to the following assignments: quant = 2; strcpy(units, "quarts"); strcpy(item, "oil"); count = 3; quant = -12.8; strcpy(units, "degrees"); count = 2; /* "C" fails to match "o" */ count = 0; /* "l" fails to match "%f" */ quant = 10.0; strcpy(units, "LBS"); strcpy(item, "fertilizer"); count = 3; count = 0; /* "100e" fails to match "%f" */ count = EOF; Forward references: the strtod function ($4.10.1.4), the strtol function ($4.10.1.5), the strtoul function ($4.10.1.6). 4.9.6.3 The printf function Synopsis #include int printf(const char *format, ...); Description The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf . Returns The printf function returns the number of characters transmitted, or a negative value if an output error occurred. 4.9.6.4 The scanf function Synopsis #include int scanf(const char *format, ...); Description The scanf function is equivalent to fscanf with the argument stdin interposed before the arguments to scanf . Returns The scanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure. 4.9.6.5 The sprintf function Synopsis #include int sprintf(char *s, const char *format, ...); Description The sprintf function is equivalent to fprintf , except that the argument s specifies an array into which the generated output is to be written, rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned sum. If copying takes place between objects that overlap, the behavior is undefined. Returns The sprintf function returns the number of characters written in the array, not counting the terminating null character. 4.9.6.6 The sscanf function Synopsis #include int sscanf(const char *s, const char *format, ...); Description The sscanf function is equivalent to fscanf , except that the argument s specifies a string from which the input is to be obtained, rather than from a stream. Reaching the end of the string is equivalent to encountering end-of-file for the fscanf function. If copying takes place between objects that overlap, the behavior is undefined. Returns The sscanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the sscanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure. 4.9.6.7 The vfprintf function Synopsis #include #include int vfprintf(FILE *stream, const char *format, va_list arg); Description The vfprintf function is equivalent to fprintf , with the variable argument list replaced by arg , which has been initialized by the va_start macro (and possibly subsequent va_arg calls). The vfprintf function does not invoke the va_end macro.rN Returns The vfprintf function returns the number of characters transmitted, or a negative value if an output error occurred. Example The following shows the use of the vfprintf function in a general error-reporting routine. #include #include void error(char *function_name, char *format, ...) { va_list args; va_start(args, format); /* print out name of function causing error */ fprintf(stderr, "ERROR in %s: ", function_name); /* print out remainder of message */ vfprintf(stderr, format, args); va_end(args); } 4.9.6.8 The vprintf function Synopsis #include #include int vprintf(const char *format, va_list arg); Description The vprintf function is equivalent to printf , with the variable argument list replaced by arg , which has been initialized by the va_start macro (and possibly subsequent va_arg calls). The vprintf function does not invoke the va_end macro.rN Returns The vprintf function returns the number of characters transmitted, or a negative value if an output error occurred. 4.9.6.9 The vsprintf function Synopsis #include #include int vsprintf(char *s, const char *format, va_list arg); Description The vsprintf function is equivalent to sprintf , with the variable argument list replaced by arg , which has been initialized by the va_start macro (and possibly subsequent va_arg calls). The vsprintf function does not invoke the va_end macro.rN If copying takes place between objects that overlap, the behavior is undefined. Returns The vsprintf function returns the number of characters written in the array, not counting the terminating null character. 4.9.7 Character input/output functions 4.9.7.1 The fgetc function Synopsis #include int fgetc(FILE *stream); Description The fgetc function obtains the next character (if present) as an unsigned char converted to an int , from the input stream pointed to by stream , and advances the associated file position indicator for the stream (if defined). Returns The fgetc function returns the next character from the input stream pointed to by stream . If the stream is at end-of-file, the end-of-file indicator for the stream is set and fgetc returns EOF . If a read error occurs, the error indicator for the stream is set and fgetc returns EOF ./112/ 4.9.7.2 The fgets function Synopsis #include char *fgets(char *s, int n, FILE *stream); Description The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s . No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array. Returns The fgets function returns s if successful. If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned. If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned. 4.9.7.3 The fputc function Synopsis #include int fputc(int c, FILE *stream); Description The fputc function writes the character specified by c (converted to an unsigned char ) to the output stream pointed to by stream , at the position indicated by the associated file position indicator for the stream (if defined), and advances the indicator appropriately. If the file cannot support positioning requests, or if the stream was opened with append mode, the character is appended to the output stream. Returns The fputc function returns the character written. If a write error occurs, the error indicator for the stream is set and fputc returns EOF . 4.9.7.4 The fputs function Synopsis #include int fputs(const char *s, FILE *stream); Description The fputs function writes the string pointed to by s to the stream pointed to by stream . The terminating null character is not written. Returns The fputs function returns EOF if a write error occurs; otherwise it returns a nonnegative value. 4.9.7.5 The getc function Synopsis #include int getc(FILE *stream); Description The getc function is equivalent to fgetc , except that if it is implemented as a macro, it may evaluate stream more than once, so the argument should never be an expression with side effects. Returns The getc function returns the next character from the input stream pointed to by stream . If the stream is at end-of-file, the end-of-file indicator for the stream is set and getc returns EOF . If a read error occurs, the error indicator for the stream is set and getc returns EOF . 4.9.7.6 The getchar function Synopsis #include int getchar(void); Description The getchar function is equivalent to getc with the argument stdin . Returns The getchar function returns the next character from the input stream pointed to by stdin . If the stream is at end-of-file, the end-of-file indicator for the stream is set and getchar returns EOF . If a read error occurs, the error indicator for the stream is set and getchar returns EOF . 4.9.7.7 The gets function Synopsis #include char *gets(char *s); Description The gets function reads characters from the input stream pointed to by stdin , into the array pointed to by s , until end-of-file is encountered or a new-line character is read. Any new-line character is discarded, and a null character is written immediately after the last character read into the array. Returns The gets function returns s if successful. If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned. If a read error occurs during the operation, the array contents are indeterminate and a null pointer is returned. 4.9.7.8 The putc function Synopsis #include int putc(int c, FILE *stream); Description The putc function is equivalent to fputc , except that if it is implemented as a macro, it may evaluate stream more than once, so the argument should never be an expression with side effects. Returns The putc function returns the character written. If a write error occurs, the error indicator for the stream is set and putc returns EOF . 4.9.7.9 The putchar function Synopsis #include int putchar(int c); Description The putchar function is equivalent to putc with the second argument stdout . Returns The putchar function returns the character written. If a write error occurs, the error indicator for the stream is set and putchar returns EOF . 4.9.7.10 The puts function Synopsis #include int puts(const char *s); Description The puts function writes the string pointed to by s to the stream pointed to by stdout , and appends a new-line character to the output. The terminating null character is not written. Returns The puts function returns EOF if a write error occurs; otherwise it returns a nonnegative value. 4.9.7.11 The ungetc function Synopsis #include int ungetc(int c, FILE *stream); Description The ungetc function pushes the character specified by c (converted to an unsigned char ) back onto the input stream pointed to by stream . The pushed-back characters will be returned by subsequent reads on that stream in the reverse order of their pushing. A successful intervening call (with the stream pointed to by stream ) to a file positioning function ( fseek , fsetpos , or rewind ) discards any pushed-back characters for the stream. The external storage corresponding to the stream is unchanged. One character of pushback is guaranteed. If the ungetc function is called too many times on the same stream without an intervening read or file positioning operation on that stream, the operation may fail. If the value of c equals that of the macro EOF , the operation fails and the input stream is unchanged. A successful call to the ungetc function clears the end-of-file indicator for the stream. The value of the file position indicator for the stream after reading or discarding all pushed-back characters shall be the same as it was before the characters were pushed back. For a text stream, the value of its file position indicator after a successful call to the ungetc function is unspecified until all pushed-back characters are read or discarded. For a binary stream, its file position indicator is decremented by each successful call to the ungetc function; if its value was zero before a call, it is indeterminate after the call. Returns The ungetc function returns the character pushed back after conversion, or EOF if the operation fails. Forward references: file positioning functions ($4.9.9). 4.9.8 Direct input/output functions 4.9.8.1 The fread function Synopsis #include size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); Description The fread function reads, into the array pointed to by ptr , up to nmemb members whose size is specified by size , from the stream pointed to by stream . The file position indicator for the stream (if defined) is advanced by the number of characters successfully read. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate. If a partial member is read, its value is indeterminate. Returns The fread function returns the number of members successfully read, which may be less than nmemb if a read error or end-of-file is encountered. If size or nmemb is zero, fread returns zero and the contents of the array and the state of the stream remain unchanged. 4.9.8.2 The fwrite function Synopsis #include size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); Description The fwrite function writes, from the array pointed to by ptr , up to nmemb members whose size is specified by size , to the stream pointed to by stream . The file position indicator for the stream (if defined) is advanced by the number of characters successfully written. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate. Returns The fwrite function returns the number of members successfully written, which will be less than nmemb only if a write error is encountered. 4.9.9 File positioning functions 4.9.9.1 The fgetpos function Synopsis #include int fgetpos(FILE *stream, fpos_t *pos); Description The fgetpos function stores the current value of the file position indicator for the stream pointed to by stream in the object pointed to by pos . The value stored contains unspecified information usable by the fsetpos function for repositioning the stream to its position at the time of the call to the fgetpos function. Returns If successful, the fgetpos function returns zero; on failure, the fgetpos function returns nonzero and stores an implementation-defined positive value in errno . Forward references: the fsetpos function ($4.9.9.3). 4.9.9.2 The fseek function Synopsis #include int fseek(FILE *stream, long int offset, int whence); Description The fseek function sets the file position indicator for the stream pointed to by stream . For a binary stream, the new position, measured in characters from the beginning of the file, is obtained by adding offset to the position specified by whence . The specified point is the beginning of the file for SEEK_SET , the current value of the file position indicator for SEEK_CUR , or end-of-file for SEEK_END . A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END . For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier call to the ftell function on the same stream and whence shall be SEEK_SET . A successful call to the fseek function clears the end-of-file indicator for the stream and undoes any effects of the ungetc function on the same stream. After an fseek call, the next operation on an update stream may be either input or output. Returns The fseek function returns nonzero only for a request that cannot be satisfied. Forward references: the ftell function ($4.9.9.4). 4.9.9.3 The fsetpos function Synopsis #include int fsetpos(FILE *stream, const fpos_t *pos); Description The fsetpos function sets the file position indicator for the stream pointed to by stream according to the value of the object pointed to by pos , which shall be a value returned by an earlier call to the fgetpos function on the same stream. A successful call to the fsetpos function clears the end-of-file indicator for the stream and undoes any effects of the ungetc function on the same stream. After an fsetpos call, the next operation on an update stream may be either input or output. Returns If successful, the fsetpos function returns zero; on failure, the fsetpos function returns nonzero and stores an implementation-defined positive value in errno . 4.9.9.4 The ftell function Synopsis #include long int ftell(FILE *stream); Description The ftell function obtains the current value of the file position indicator for the stream pointed to by stream . For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read. Returns If successful, the ftell function returns the current value of the file position indicator for the stream. On failure, the ftell function returns -1L and stores an implementation-defined positive value in errno . 4.9.9.5 The rewind function Synopsis #include void rewind(FILE *stream); Description The rewind function sets the file position indicator for the stream pointed to by stream to the beginning of the file. It is equivalent to (void)fseek(stream, 0L, SEEK_SET) except that the error indicator for the stream is also cleared. Returns The rewind function returns no value. 4.9.10 Error-handling functions 4.9.10.1 The clearerr function Synopsis #include void clearerr(FILE *stream); Description The clearerr function clears the end-of-file and error indicators for the stream pointed to by stream . Returns The clearerr function returns no value. 4.9.10.2 The feof function Synopsis #include int feof(FILE *stream); Description The feof function tests the end-of-file indicator for the stream pointed to by stream . Returns The feof function returns nonzero if and only if the end-of-file indicator is set for stream . 4.9.10.3 The ferror function Synopsis #include int ferror(FILE *stream); Description The ferror function tests the error indicator for the stream pointed to by stream . Returns The ferror function returns nonzero if and only if the error indicator is set for stream . 4.9.10.4 The perror function Synopsis #include void perror(const char *s); Description The perror function maps the error number in the integer expression errno to an error message. It writes a sequence of characters to the standard error stream thus: first (if s is not a null pointer and the character pointed to by s is not the null character), the string pointed to by s followed by a colon and a space; then an appropriate error message string followed by a new-line character. The contents of the error message strings are the same as those returned by the strerror function with argument errno , which are implementation-defined. Returns The perror function returns no value. Forward references: the strerror function ($4.11.6.2).