C Programming/stdio.h/Function reference

Prototype
void clearerr( FILE *stream );

Description
The clearerr function resets the error flags and EOF indicator for the given stream. When an error occurs, you can use perror to figure out which error actually occurred.

fclose
fclose is a C function belonging to the ANSI C standard library, and included in the file stdio.h. Its purpose is close a stream and all the structure associated with it. Usually the stream is an open file. has the following prototype:



It takes one argument: a pointer to the FILE structure of the stream to close, eg: This line call the function fclose to close FILE stream structure pointed by my_file_pointer.

The return value is an integer with the following meaning:
 * 0 (zero): the stream was closed successfully;
 * EOF: an error occurred;

One can check for an error by reading errno. fclose has undefined behavior if it attempts to close a file pointer that isn't currently assigned to a file - in many cases, this results in a program crash.

It is usually a wrapper for a close system call.

Example usage
The above program opens a file called myfile.txt and scans for an integer in it.

feof
feof is a C standard library function declared in the header stdio.h. Its primary purpose is to distinguish between cases where a stream operation has reached the end of a file and cases where the  ("end of file") error code has been returned as a generic error indicator, without the end of the file's actually having been reached.

Function prototype
The function is declared as follows:

It takes one argument: a pointer to the  structure of the stream to check.

Return value
The return value of the function is an integer. A nonzero value signifies that the end of the file has been reached; a value of zero signifies that it has not.

Pitfalls
A common misuse of the function is trying to use feof "preemptively". However, this doesn't work correctly, as feof is only set for a descriptor after a reading function has failed.

Prototype
int fgetc(FILE *stream)

Description
The fgetc function in the C standard library  is used to read a character from a file stream. If successful, fgetc returns a character from the file at its current position. If unsuccessful, fgetc returns an error code. For text files (as opposed to binary files), the characters with values 25 and 26 (the substitute character and the escape character) may render the input stream inoperable afterward, instead returning a single maximal value.

Error codes:
 * -1: Bad argument: not integer
 * -2: Bad argument: out of range
 * -3: File was not open

fgetpos
fgetpos is a function in the I/O section of the C standard library.

Usage

 * int fgetpos(FILE *stream, fpos_t *pos);

fgetpos will retrieve the file offset (in bytes) from stdio stream stream into storage of type fpos t pointed to by variable pos, which should be allocated by the caller. This variable should only be used for subsequent calls to fsetpos. A separate function, <tt>ftell</tt> can be used instead in order to retrieve the value of the file offset as a long integer.

The return value is 0 on successful completion, or -1 on error (in which case <tt>errno</tt> is set accordingly).

fgets
fgets is a function in the C programming language that reads a limited number of characters from a given file stream source into an array of characters. stands for file get string. It is included in the C standard library header file. The prototype of the function is as follows:

The function terminates reading either after a new-line character is found or end-of-file is reached, or after (length - 1) characters have been read. If a new-line was reached it is included in the string as the last character before the null character. The length argument includes space needed for the null character which will be appended to the end of the string. As a result, to read N characters, the length specification must be specified as N+1. The string read is returned if at least one character was read and no error occurred, otherwise a NULL-pointer is returned.

The stream argument specifies the stream from which the string be read. is commonly used here, for reading from the standard input. Otherwise, a  value returned by the   function is used.

Sample usage
The following code reads characters from the console input and prints them out 20 in a line with the puts function until an EOF occurs.

Use in POSIX utilities
For compliance with POSIX utility line lengths, the definition  (generally found in limits.h) is often used to size the character buffer.

Limitations
The fixed buffer size imposed by  is cumbersome in applications which need to handle arbitrarily long lines of text.

POSIX.1-2008-conforming systems provide a function called  (originally a GNU extension ), which will read an entire line, reallocating the buffer if it is not long enough.

Advanced applications can avoid buffer limitations by using mmap.

fopen
fopen, as implemented in glibc and musl will use the open system call.

Opening a file using fopen
A file is opened using, which returns an I/O stream attached to the specified file or other device from which reading and writing can be done. If the function fails, it returns a null pointer.

The related C library function  performs the same operation after first closing any open stream associated with its parameters.

They are defined as

The  function is essentially a slightly higher-level wrapper for the   system call of Unix operating systems. In the same way,  is often a thin wrapper for the Unix system call , and the C   structure itself often corresponds to a Unix file descriptor. In POSIX environments, the  function can be used to initialize a   structure from a file descriptor; however, file descriptors are a purely Unix concept not present in standard C.

The  parameter to   and   must be a string that begins with one of the following sequences:

The "<tt>b</tt>" stands for binary. The C standard provides for two kinds of files—text files and binary files—although operating systems are not required to distinguish between the two. A text file is a file consisting of text arranged in lines with some sort of distinguishing end-of-line character or sequence (in Unix, a bare line feed character; in Microsoft Windows, a carriage return followed by a line feed). When bytes are read in from a text file, an end-of-line sequence is usually mapped to a linefeed for ease in processing. When a text file is written to, a bare linefeed is mapped to the OS-specific end-of-line character sequence before writing. A binary file is a file where bytes are read in "raw", and delivered "raw", without any kind of mapping.

When a file is opened with update mode ( '<tt>+</tt>' as the second or third character in the mode argument), both input and output may be performed on the associated stream. However, writes cannot be followed by reads without an intervening call to  or to a file positioning function (,  , or  ), and reads cannot be followed by writes without an intervening call to a file positioning function.

Writing and appending modes will attempt to create a file of the given name, if no such file already exists. As mentioned above, if this operation fails,  will return.

Glibc/musl notes
Musl and Glibc support the <tt>e</tt> mode on Linux, which sets <tt>O_CLOEXEC</tt> on the new file descriptor. <tt>O_CLOEXEC</tt> is a Linux 2.6 feature, documented in the Linux man-pages project:

"Enable the close-on-exec flag for the new file descriptor. Specifying this flag permits a program to avoid additional fcntl(2) F_SETFD operations to set the FD_CLOEXEC flag. Additionally, use of this flag is essential in some multithreaded programs since using a separate fcntl(2) F_SETFD operation to set the FD_CLOEXEC flag does not suffice to avoid race conditions where one thread opens a file descriptor at the same time as another thread does a fork(2) plus execve(2)."

See http://danwalsh.livejournal.com/53603.html

See musl cgit for the Musl implementation.

fputs
fputs is a function in C programming language that writes an array of characters to a given file stream. stands for file put string. It is included in the C standard library header file.

The function  terminates after reaching terminating null character. The null character is not copied to the stream. The prototype of the function is as follows:

The stream argument specifies the stream to which the string will be written. is commonly used here, for writing to the standard output. Otherwise, a  value returned by the   function is used.

Sample usage
The following example is 'hello world' program using :

The following is a program that asks the user for his name and then writes it out:

fread
fread is a function that reads buffered binary input from a file. It is included from the stdio.h header file in the standard C library.



The  function copies   items of data of size   from the named input   into an array pointed to by. An item of data is a sequence of bytes (not necessarily terminated by a null byte) of length. stops appending bytes when  items have been read, end of file has been reached, or an error has occurred. Upon returning,  sets the file pointer in the stream pointing to the byte past the last byte that has been read. The contents of  remain unchanged. The  function returns the number of items actually read. If  is zero, no action is taken and the function will return 0.

Diagnostics
The function may fail with the following error codes:
 * EAGAIN - Cannot read the input stream immediately without blocking the process, and the O_NONBLOCK flag is set for the file descriptor associated with stream.
 * EBADF - Not a valid file descriptor open for reading.
 * EINTR - The read operation was terminated by a signal before any data was read.
 * EIO - Cannot read from the controlling terminal. This happens when the process is in a background process group and the attempt by the process to read from its controlling terminal fails, either because the process group is orphaned, or because the process is ignoring or blocking the SIGTTIN signal.
 * ENOMEM - Insufficient storage space is available.
 * ENXIO - Attempt to read from a non-existent device, or from a device whose capabilities are exceeded.

fseek
fseek is a C function belonging to the ANSI C standard library, and included in the file stdio.h. Its purpose is to change the file position indicator for the specified stream. Because fseek uses 32 bit values on many platforms it has a limitation of maximum 2 gigabyte seeks. fseeko64 would be used for larger offsets.

Prototype


The fseek function moves the file pointer associated with the stream to a new location that is offset bytes from origin

Argument meaning:
 * stream_pointer is a pointer to the stream FILE structure of which the position indicator should be changed;
 * offset is a long integer which specifies the number of bytes from origin where the position indicator should be placed;
 * origin is an integer which specifies the origin position. It can be:
 * SEEK_SET: origin is the start of the stream
 * SEEK_CUR: origin is the current position
 * SEEK_END: origin is the end of the stream

Return value
The return value is an integer which mean:
 * 0 (zero) : function performed successfully in the stream
 * nonzero : an error occurred
 * On devices incapable of seeking, the return value is undefined.

Note that each error number has a distinct meaning. The meaning can be revealed by checking errno.h.

Example
This program code opens a file called file.bin in read-only mode. The length of the file is determined by seeking to the end and then reading back the position of the file pointer.

fsetpos
fsetpos positions stream at the position recorded by fgetpos in *ptr.fsetpos returns non-zero on error.It is one of the file positioning function.

Prototype
int fsetpos(file *stream, const fpos_t *ptr)

ftell
The function ftell returns the current offset in a stream in relation to the first byte. It returns the current file position for stream, or -1 if an error occurs.

fwprintf
<tt>fwprintf</tt> is a C standard library function as defined in wchar.h. The required headers are whar.h and stdio.h. It is the wide character version of fprintf. It's function signature is int fwprintf(FILE *fp, const wchar_t *format, argument list); In signature of the fwprintf, fp is a stream to which you want to send output. format is wide character stream that specifies the format of output.The formatting string takes care of additional arguments you need to provide.

Usage
fwprintf puts output on the named output stream. fwprintf performs wide character output to stream and this stream is not byte oriented The fwprintf is the function which converts all the arguments specified in the argument list in accordance with wide character format specifier in format.The fwprintf function writes output to the stream ,under control of the wide string pointed to by format.

Format
fwprintf function can convert, print and format its arguments in the parenthesis which converts the format wide characters string. Here the format consists of either numbered argument specifications such as "%n$"and "*m$" or unnumbered arguments conversion specifiers such as % and *.But both cannot be.

Return
fwprintf returns the number of wide characters used excluding the NULL character. If an error occurs ,it returns a negative number.

fwrite
The  and   functions respectively provide the file operations of input and output. and  are declared in. It usually wraps write system call.

Writing a file using fwrite
fwrite is defined as

function writes a block of data to the stream. It will write an array of  elements to the current position in the stream. For each element, it will write  bytes. The position indicator of the stream will be advanced by the number of bytes written successfully.

The function will return the number of elements written successfully. The return value will be equal to  if the write completes successfully. In case of a write error, the return value will be less than.

Example
The following program opens a file named <tt>sample.txt</tt>, writes an array of characters to the file, and closes it.

getc
getc is one of the character input functions. getc reads the next character from a file, it takes a file pointer to the file. It is the simplest function to read a file.

Like getchar, getc may be implemented macro instead of function. getc is equivalent to fgetc. getc returns the next character from the stream referred to by fp; it returns EOF for End Of File or error.

Syntax
int getc( FILE * stream); Here, parameter stream is the pointer to a FILE object which identify the stream on which the operation is to be performed.

Example
/*getc example*/

Above program read the file called myfile.txt character by character and uses n variable to count '#' character contained in file.

Return Value
Character read is returned as an int value.

If the End-of-File is reached or error in reading occurs, function returns EOF and corresponding error indicator. We can use either ferror or feof to determine whether an error happened or EOF reached.

perror
The POSIX error function, perror, is used in C and C++ to print an error message to stderr, based on the error state stored in errno. It prints str and an implementation-defined error message corresponding to the global variable errno.

History
The definition of perror was first released in Issue 1 of the System V Interface Definition.

Semantics
If the parameter prefix is non-NULL, perror will first print prefix followed by a colon and a space to standard error. Then, it will print the result of strerror to standard error, followed by a newline character. For instance the above example may print

open: Permission denied

printf


Printf functions (which stands for "print formatted") are a class of functions typically associated with some types of programming languages. They accept a string parameter called the format string, which specifies a method for rendering an arbitrary number of varied data type parameter(s) into a string. This string is then by default printed on the standard output stream, but variants exist that perform other tasks with the result. Characters in the format string are usually copied literally into the function's output, with the other parameters being rendered into the resulting text at points marked by format specifiers, which are typically introduced by a % character.

Timeline
Many programming languages implement a   function, to output a formatted string. It originated from the C programming language, where it has a prototype similar to the following: The string constant  provides a description of the output, with placeholders marked by "%" escape characters, to specify both the relative location and the type of output that the function should produce. The return value yields the number of printed characters.

Fortran, COBOL
Fortran's variadic  statement references a non-executable   statement. will print the following ( after advancing to a new line, because of the leading blank character if directed to a printing device) :

COBOL provides formatting via hierarchical data structure specification: ...

1960s: BCPL, ALGOL 68, Multics PL/I
C's variadic  has its origins in BCPL's   function.

ALGOL 68 Draft and Final report had the functions  and , subsequently these were revised out of the original language and replaced with the now more familiar   and. printf(($"Color "g", number1 "6d,", number2 "4zd,", hex "16r2d,", float "-d.2d,", unsigned value"-3d"."l$, "red", 123456, 89, BIN 255, 3.14, 250));

Multics has a standard function called  with a wide variety of control codes. It was based on a machine-language facility from Multics's BOS (Bootstrap Operating System).

1970s: C, Lisp
will print the following line (including new-line character, \n): Color red, number1 123456, number2 00089, hex ff, float 3.14, unsigned value 250.

The  function returns the number of characters printed, or a negative value if an output error occurs.

Common Lisp has the  function.

prints  on the standard output stream. If the first argument is, format returns the string to its caller. The first argument can also be any output stream. was introduced into ZetaLisp at MIT in 1978, based on the Multics, and was later adopted into the Common Lisp standard.

1980s: Perl, Shell
Perl also has a  function. Common Lisp has a format function which acts according to the same principles as, but uses different characters for output conversion. The GLib library contains, an implementation of.

Some Unix systems have a  program for use in shell scripts. This can be used instead of echo in situations where the latter is not portable. For example: may be rewritten portably as:

1990s: PHP, Python
1991: Python's  operator harkens to  's syntax when interpolating the contents of a tuple. This operator can, for example, be used with the  function:

Version 2.6 of Python included the  which is preferred to the obsolete   which may go away in future versions of Python:

1995: PHP also has the  function, with the same specifications and usage as that in C/C++. MATLAB does not have, but does have its two extensions   and   which use the same formatting strings. returns a formatted string instead of producing a visual output.

2000s: Java
2004: Java supported  from version 1.5 onwards as a member of the  class, giving it the functionality of both the   and fprintf functions. At the same time -like functionality was added to the   class by adding the   method. Unlike most other implementations, Java's implementation of  throws an exception on encountering a malformed format string.

Related functions
The ANSI C standard specifies a number of variations of printf for situations where the output stream is not the default, where the parameter list is in a different form, where the output is targeting memory rather than a file descriptor, and so on. The printf function itself is often merely a wrapper, with defaults, around one of these:

fprintf
  enables printf output to be written to any file. Programmers frequently use it to print errors, by writing to the standard error device, but it can operate with any file opened with the  (or  ) function.

sprintf
  prints to a string ( array) instead of standard output. Users of  must ensure, via calculation or via a guard page, that the resulting string will not be larger than the memory allocated for str. Failure to ensure this can allow a buffer overflow to occur.

In higher-level languages such as PHP the  function does not have the   argument. Instead, it returns the formatted output string. The prototype in PHP is like this:

Buffer safety and sprintf
In ISO C99,   was introduced as an alternative to   that can help avoid the risk of a buffer overflow:

is guaranteed not to write more than size bytes into str, so use of it can help avoid the risk of a buffer overflow, as in the following code fragment: If username in the above example causes result to exceed 49 bytes in length, the function will limit the string that gets saved in buf by cutting off final bytes (truncating). The null terminator will always be written to the 50th location so the result is always null terminated. Additionally, the return code of  indicates how many bytes (not counting the null) the function would have written to the string had enough space existed. Systems can use this information to allocate a new (larger) buffer if they require the whole string.

A number of  implementations deviated from the above description, in particular many Windows libraries, glibc before version 2.0.6, and Solaris. The most common mistake was returning -1 on truncation rather than the length needed. More troublesome were implementations that did not write the null terminator on truncation, or returned size-1 (making it impossible to detect truncation). These deviations make writing portable safe code using  harder than it should be.

Another safe  alternative is   which is a GNU extension:

automatically allocates enough memory to hold the final string. It sets  to a pointer to the resulting string, or to an undefined value if an error occurred (glibc is notable in being the only implementation that doesn't always set   to NULL on error). The programmer using  has the responsibility of freeing the allocated memory after use. Though not part of any standard,  comes in the C libraries of several operating systems (including OpenBSD, FreeBSD, and NetBSD) and on other platforms in the libiberty library.

GLib provides yet another safe alternative:, which allocates enough memory, but, unlike  , returns the resulting string as its return value rather than via the first argument.

C++ alternatives to sprintf for numeric conversion
The standard method for string formatting and the conversion of other types to strings in C++ is iostream. Unlike printf, the iostream standard library is type-safe and extensible.

A common programming task is to convert a numeric type into a string (char buffer). The  family, while useful, may be overkill for such a simple task. In addition many programs using these are not designed to handle the variations in output when the locale changes.

A number of alternative means in C/C++ have been developed:
 * Boost::lexical_cast
 * Boost::format
 * Loki::SafeFormat
 * itoa (nonstandard)
 * std::to_string (C++11)
 * C++ Format (cppformat)

vprintf, vfprintf, vsprintf, vsnprintf, and vasprintf
These are analogous to the above functions without the vs, except that they use variable argument lists. These functions offer the ability for programmers to essentially create their own printf variants. For instance, a programmer could write a function

which would use the  macro to obtain a   variable from the extra parameters, print a message on the standard error device using , clean up after the   variable with the   macro, and finally perform the necessary tasks to cleanly shut down the program.

Another common application of these functions is to write a custom printf that prints to a different target than a file. For instance, a graphical library might provide a printf-like function with X and Y coordinates:

This would work by temporarily saving the string to a private buffer using  or.

Format placeholders
Formatting takes place via placeholders within the format string. For example, if a program wanted to print out a person's age, it could present the output by prefixing it with "Your age is ". To denote that we want the integer for the age to be shown immediately after that message, we may use the format string: "Your age is %d."

The syntax for a format placeholder is


 * Parameter can be omitted or can be:
 * {| class="wikitable"

! Character ! Description "17 0x11; 16 0x10"
 * n is the number of the parameter to display using this format specifier, allowing the parameters provided to be output multiple times, using varying format specifiers or in different orders. This is a POSIX extension and not in C99. Example:  produces
 * n is the number of the parameter to display using this format specifier, allowing the parameters provided to be output multiple times, using varying format specifiers or in different orders. This is a POSIX extension and not in C99. Example:  produces
 * n is the number of the parameter to display using this format specifier, allowing the parameters provided to be output multiple times, using varying format specifiers or in different orders. This is a POSIX extension and not in C99. Example:  produces
 * }


 * Flags can be zero or more (in any order) of:
 * {| class="wikitable"

! Character ! Description
 * (minus)
 * Left-align the output of this placeholder (the default is to right-align the output).
 * (plus)
 * Prepends a plus for positive signed-numeric types. positive = ' ', negative = ' '. (the default doesn't prepend anything in front of positive numbers).
 * (space)
 * Prepends a space for positive signed-numeric types. positive = ' ', negative = ' '. This flag is ignored if the '+' flag exists. (the default doesn't prepend anything in front of positive numbers).
 * (zero)
 * Prepends zeros for numbers when the width option is specified. (the default prepends spaces).
 * Prepends a space for positive signed-numeric types. positive = ' ', negative = ' '. This flag is ignored if the '+' flag exists. (the default doesn't prepend anything in front of positive numbers).
 * (zero)
 * Prepends zeros for numbers when the width option is specified. (the default prepends spaces).
 * Prepends zeros for numbers when the width option is specified. (the default prepends spaces).

Example:  produces " ", while   produces in " ".
 * (hash)
 * Alternate form. For ' ' and ' ', trailing zeros are not removed. For ' ', ' ', ' ', ' ', ' ', ' ', the output always contains a decimal point. For ' ', ' ', ' ', or ' ', ' ', ' ', respectively, is prepended to non-zero numbers.
 * }
 * }


 * Width specifies a minimum number of characters to output, and is typically used to pad fixed-width fields in tabulated output, where the fields would otherwise be smaller, although it does not cause truncation of oversized fields. A leading zero in the width value is interpreted as the zero-padding flag mentioned above, and a negative value is treated as the positive value in conjunction with the left-alignment "-" flag also mentioned above.
 * Precision usually specifies a maximum limit on the output, depending on the particular formatting type. For floating point numeric types, it specifies the number of digits to the right of the decimal point that the output should be rounded.  For the string type, it limits the number of characters that should be output, after which the string is truncated.


 * Length can be omitted or be any of:
 * {| class="wikitable"

! Character ! Description
 * For integer types, causes  to expect an   sized integer argument which was promoted from a.
 * For integer types, causes  to expect an   sized integer argument which was promoted from a.
 * For integer types, causes  to expect a   sized integer argument.
 * For integer types, causes  to expect a   sized integer argument.
 * For floating point types, causes  to expect a   argument.
 * For integer types, causes  to expect a   sized integer argument.
 * For integer types, causes  to expect a   sized integer argument.
 * For integer types, causes  to expect a   sized integer argument.
 * }
 * For integer types, causes  to expect a   sized integer argument.
 * For floating point types, causes  to expect a   argument.
 * For integer types, causes  to expect a   sized integer argument.
 * For integer types, causes  to expect a   sized integer argument.
 * For integer types, causes  to expect a   sized integer argument.
 * }
 * For integer types, causes  to expect a   sized integer argument.
 * For integer types, causes  to expect a   sized integer argument.
 * For integer types, causes  to expect a   sized integer argument.
 * }
 * For integer types, causes  to expect a   sized integer argument.
 * For integer types, causes  to expect a   sized integer argument.
 * }
 * For integer types, causes  to expect a   sized integer argument.
 * }
 * }

Additionally, several platform-specific length options came to exist prior to widespread use of the ISO C99 extensions:
 * {| class="wikitable"

! Characters ! Description
 * For signed integer types, causes  to expect   sized integer argument; for unsigned integer types, causes   to expect   sized integer argument. Commonly found in Win32/Win64 platforms.
 * For integer types, causes  to expect a 32-bit (double word) integer argument.  Commonly found in Win32/Win64 platforms.
 * For integer types, causes  to expect a 64-bit (quad word) integer argument.  Commonly found in Win32/Win64 platforms.
 * For integer types, causes  to expect a 64-bit (quad word) integer argument.  Commonly found in BSD platforms.
 * }
 * For integer types, causes  to expect a 32-bit (double word) integer argument.  Commonly found in Win32/Win64 platforms.
 * For integer types, causes  to expect a 64-bit (quad word) integer argument.  Commonly found in Win32/Win64 platforms.
 * For integer types, causes  to expect a 64-bit (quad word) integer argument.  Commonly found in BSD platforms.
 * }
 * For integer types, causes  to expect a 64-bit (quad word) integer argument.  Commonly found in BSD platforms.
 * }
 * For integer types, causes  to expect a 64-bit (quad word) integer argument.  Commonly found in BSD platforms.
 * }

ISO C99 includes the  header file that includes a number of macros for use in platform-independent   coding. Example macros include:
 * {| class="wikitable"

! Characters ! Description
 * Typically equivalent to  (Win32/Win64) or
 * Typically equivalent to  (Win32/Win64),   (32-bit platforms) or   (64-bit platforms)
 * Typically equivalent to  (Win32/Win64) or
 * Typically equivalent to  (Win32/Win64),   (32-bit platforms) or   (64-bit platforms)
 * Typically equivalent to  (Win32/Win64) or
 * Typically equivalent to  (Win32/Win64),   (32-bit platforms) or   (64-bit platforms)
 * Typically equivalent to  (Win32/Win64),   (32-bit platforms) or   (64-bit platforms)
 * }
 * Typically equivalent to  (Win32/Win64) or
 * Typically equivalent to  (Win32/Win64),   (32-bit platforms) or   (64-bit platforms)
 * Typically equivalent to  (Win32/Win64) or
 * Typically equivalent to  (Win32/Win64),   (32-bit platforms) or   (64-bit platforms)
 * Typically equivalent to  (Win32/Win64),   (32-bit platforms) or   (64-bit platforms)
 * }
 * Typically equivalent to  (Win32/Win64) or
 * Typically equivalent to  (Win32/Win64),   (32-bit platforms) or   (64-bit platforms)
 * Typically equivalent to  (Win32/Win64),   (32-bit platforms) or   (64-bit platforms)
 * }
 * Typically equivalent to  (Win32/Win64),   (32-bit platforms) or   (64-bit platforms)
 * }
 * Typically equivalent to  (Win32/Win64),   (32-bit platforms) or   (64-bit platforms)
 * }


 * Type can be any of:
 * {| class="wikitable"

! Character ! Description
 * as a signed decimal number. ' ' and ' ' are synonymous for output, but are different when used with  for input.
 * Print decimal.
 * in normal (fixed-point) notation. 'f' and 'F' only differs in how the strings for an infinite number or NaN are printed ('inf', 'infinity' and 'nan' for 'f', 'INF', 'INFINITY' and 'NAN' for 'F').
 * value in standard form ([-]d.ddd e[+/-]ddd). An E conversion uses the letter E (rather than e) to introduce the exponent. The exponent always contains at least two digits; if the value is zero, the exponent is 00. In Windows, the exponent contains three digits by default, e.g. 1.5e002, but this can be altered by Microsoft-specific   function.
 * in either normal or exponential notation, whichever is more appropriate for its magnitude. 'g' uses lower-case letters, 'G' uses upper-case letters. This type differs slightly from fixed-point notation in that insignificant zeroes to the right of the decimal point are not included.  Also, the decimal point is not included on whole numbers.
 * as a hexadecimal number. 'x' uses lower-case letters and 'X' uses upper-case.
 * in octal.
 * null-terminated string.
 * (character).
 * (pointer to void) in an implementation-defined format.
 * Print nothing, but write number of characters successfully written so far into an integer pointer parameter.
 * a literal '%' character (this type doesn't accept any flags, width, precision or length).
 * }
 * in either normal or exponential notation, whichever is more appropriate for its magnitude. 'g' uses lower-case letters, 'G' uses upper-case letters. This type differs slightly from fixed-point notation in that insignificant zeroes to the right of the decimal point are not included.  Also, the decimal point is not included on whole numbers.
 * as a hexadecimal number. 'x' uses lower-case letters and 'X' uses upper-case.
 * in octal.
 * null-terminated string.
 * (character).
 * (pointer to void) in an implementation-defined format.
 * Print nothing, but write number of characters successfully written so far into an integer pointer parameter.
 * a literal '%' character (this type doesn't accept any flags, width, precision or length).
 * }
 * null-terminated string.
 * (character).
 * (pointer to void) in an implementation-defined format.
 * Print nothing, but write number of characters successfully written so far into an integer pointer parameter.
 * a literal '%' character (this type doesn't accept any flags, width, precision or length).
 * }
 * (pointer to void) in an implementation-defined format.
 * Print nothing, but write number of characters successfully written so far into an integer pointer parameter.
 * a literal '%' character (this type doesn't accept any flags, width, precision or length).
 * }
 * Print nothing, but write number of characters successfully written so far into an integer pointer parameter.
 * a literal '%' character (this type doesn't accept any flags, width, precision or length).
 * }
 * a literal '%' character (this type doesn't accept any flags, width, precision or length).
 * }

The width and precision formatting parameters may be omitted, or they can be a fixed number embedded in the format string, or passed as another function argument when indicated by an asterisk "*" in the format string. For example  will result in   being printed, with a total width of 5 characters, and   will result in "abc" being printed.

If the syntax of a conversion specification is invalid, behavior is undefined, and can cause program termination. If there are too few function arguments provided to supply values for all the conversion specifications in the template string, or if the arguments are not of the correct types, the results are also undefined. Excess arguments are ignored. In a number of cases, the undefined behavior has led to "Format string attack" security vulnerabilities.

Some compilers, like the GNU Compiler Collection, will statically check the format strings of printf-like functions and warn about problems (when using the flags  or  ). GCC will also warn about user-defined printf-style functions if the non-standard "format" __attribute__ is applied to the function.

Risks of using field width versus explicit delimiters in tabular output
Using only field widths to provide for tabulation, as with a format like " " for three integers in three 8-character columns, will not guarantee that field separation will be retained if large numbers occur in the data. Loss of field separation can easily lead to corrupt output. In systems which encourage the use of programs as building blocks in scripts, such corrupt data can often be forwarded into and corrupt further processing, regardless of whether the original programmer expected the output would only be read by human eyes. Such problems can be eliminated by including explicit delimiters, even spaces, in all tabular output formats. Simply changing the dangerous example from before to " " addresses this, formatting identically until numbers become larger, but then explicitly preventing them from becoming merged on output due to the explicitly-included spaces. Similar strategies apply to string data.

Custom format placeholders
There are a few implementations of -like functions that allow extensions to the escape-character-based mini-language, thus allowing the programmer to have a specific formatting function for non-builtin types. One of the most well-known is the (now deprecated) glibc's. However, it is rarely used due to the fact that it conflicts with static format string checking. Another is Vstr custom formatters, which allows adding multi-character format names, and can work with static format checkers.

Some applications (like the Apache HTTP Server) include their own -like function, and embed extensions into it. However these all tend to have the same problems that  has.

Most non-C languages that have a -like function work around the lack of this feature by just using the " " format and converting the object to a string representation. C++ offers a notable exception, in that it has a  function inherited from its C history, but also has a completely different mechanism that is preferred.

putc
putc is the function in stdio.h. It is simplest way to write the file once it is open. It writes the character to stream and advances the position indicator. It is output function. The character is written at the current position of the stream as indicated by the internal position indicator, which is then advanced one character.

is equivalent to  and also expects a stream as parameter, but   may be implemented as a macro, so the argument passed should not be an expression with potential side effects.

See putchar for a similar function without stream parameter.

Parameters

 * character: Character to be written. The character is passed as its int promotion.
 * stream: Pointer to a FILE object that identifies the stream where the character is to be written.

Return value
If there are no errors, the same character that has been written is returned. If an error occurs, EOF is returned and the error indicator is set.

Example
/* putc example: alphabet writer */

Output
This example program creates a file called alphabet.txt and writes ABCDEFGHIJKLMNOPQRSTUVWXYZ to it.

putchar
putchar is a function in the C programming language that writes a single character to the standard output stream, stdout. Its prototype is as follows:

The character to be printed is fed into the function as an argument, and if the writing is successful, the argument character is returned. Otherwise, end-of-file is returned.

The  function is specified in the C standard library header file stdio.h.

Sample usage
The following program uses  to read characters into an array and print them out using the   function after an end-of-file character is found.

The program specifies the reading length's maximum value at 1000 characters. It will stop reading either after reading 1000 characters or after reading in an end-of-file indicator, whichever comes first.

puts
is a function used to output a string (plus a newline), for example, output (on stdout): welcome to WIKIPEDIA!!!

Differences from printf:

1.  prints a newline after the supplied text

2.  prints the string as is (it does not process % codes).

We can also pass a variable to, for example, output: welcome to WIKIPEDIA!!!

has the following prototype:

int puts(const char *str)

It will print each byte at  until a null is reached, then print a newline. returns the number of bytes written (including the newline), or EOF (if an error occurred.)

To print a string without processing % codes, or outputting a newline, try:

remove
remove is a function in C programming language that removes a certain file. It is included in the C standard library header file.

The prototype of the function is as follows:

If successful, the function returns zero. Nonzero value is returned on failure and  variable is set to corresponding error code.

Sample usage
The following program demonstrates common usage of :

To implement a simple remove utility:

rename
rename is a function in the C programming language that renames a certain file.

The prototype of the function is:

Zero is returned upon success. Other integers are returned upon failure and  is set to an error code in this case.

The rename function is specified in the stdio.h library header file in C and the  header in C++. It is specified in ANSI C.

In POSIX, rename will fail (with EXDEV) if the old and new names are on different mounted file systems. If a call to rename succeeds it is guaranteed to have been atomic from the point of view of the current host (i.e., another program would only see the file with the old name or the file with the new name, not both or neither of them).

The Windows C library version of rename fails if the destination file already exists (POSIX would only fail if the user does not have permission to remove the destination file). Although the underlying WIN32 call has (since Win2K) had an option to replicate the POSIX atomic behavior, the library has never been fixed to use this.

rewind
rewind is a function in the C programming language that is specified in the  library header file. The function moves the file position indicator to the beginning of the specified stream, while also clearing the error and EOF flags associated with that stream.

acts as if  was called for the stream passed, except that   causes the error indicator to also be cleared.

scanf
scanf is a function that reads data with specified format from a given string stream source, originated from C programming language, and is present in many other programming languages.

The  function prototype is:

The function returns the total number of items successfully matched, which can be less than the number requested. If the input stream is exhausted or reading from it otherwise fails before any items are matched, EOF is returned.

So far as is traceable, "scanf" stands for "scan format", because it scans the input for valid tokens and parses them according to a specified format.

Usage
The  function is found in C, in which it reads input for numbers and other datatypes from standard input (often a command line interface or similar kind of a text user interface).

The following shows code in C that reads a variable number of unformatted decimal integers from the standard input and prints out each of them on a separate line:

After being processed by the program above, a messy list of integers such as

456 123 789    456 12 456 1       2378

will appear neatly as: 456 123 789 456 12 456 1 2378

To print out a word:

No matter what the datatype the programmer wants the program to read, the arguments (such as  above) must be pointers pointing to memory. Otherwise, the function will not perform correctly because it will be attempting to overwrite the wrong sections of memory, rather than pointing to the memory location of the variable you are attempting to get input for.

As  is designated to read only from standard input, many programming languages with interfaces, such as PHP, have derivatives such as   and   but not   itself.

Derivatives
Depending on the actual source of input, programmers can use different derivatives of. Two common examples are  and.

fscanf
The fscanf derivative reads input from a specified file stream. The prototypes are as follows:

(C or C++)

(PHP)

The  derivative works like the original   function - parts of the input, once read, will not be read again until the file is closed and reopened.

sscanf
The sscanf derivative reads input from a character string passed as the first argument. One important different from fscanf is that the string is read from the beginning every time the function is called. There is no 'pointer' that is incremented upon a successful read operation. The prototypes are as follows:

(C or C++)

(PHP)

vscanf, vsscanf, and vfscanf
These are like the same functions without the  prefix, except they take their arguments from a. (See stdarg.h.) These variants may be used in variable-argument functions.

Format string specifications
The formatting placeholders in  are more or less the same as that in , its reverse function.

There are rarely constants (i.e. characters that are not formatting placeholders) in a format string, mainly because a program is usually not designed to read known data. The exception is one or more whitespace characters, which discards all whitespace characters in the input.

Some of the most commonly used placeholders follow:
 * : Scan an integer as a signed decimal number.
 * : Scan an integer as a signed number. Similar to , but interprets the number as hexadecimal when preceded by   and octal when preceded by  .  For example, the string   would be read as 31 using  , and 25 using  . The flag   in   indicates conversion to a   and   conversion to a.
 * : Scan for decimal  (Note that in the C99 standard the input value minus sign is optional, so if a negative number is read, no errors will arise and the result will be the two's complement. See  .) Correspondingly,   scans for an   and   for an.
 * : Scan a floating-point number in normal (fixed-point) notation.
 * ,  : Scan a floating-point number in either normal or exponential notation.   uses lower-case letters and   uses upper-case.
 * ,  : Scan an integer as an unsigned hexadecimal number.
 * : Scan an integer as an octal number.
 * : Scan a character string. The scan terminates at whitespace. A null character is stored at the end of the string, which means that the buffer supplied must be at least one character longer than the specified input length.
 * : Scan a character (char). No null character is added.
 * : Space scans for whitespace characters.
 * : Scan as a double floating-point number.
 * : Scan as a long double floating-point number.

The above can be used in compound with numeric modifiers and the,   modifiers which stand for "long" in between the percent symbol and the letter. There can also be numeric values between the percent symbol and the letters, preceding the  modifiers if any, that specifies the number of characters to be scanned. An optional asterisk right after the percent symbol denotes that the datum read by this format specifier is not to be stored in a variable. No argument behind the format string should be included for this dropped variable.

The  modifier in printf is not present in scanf, causing differences between modes of input and output. The  and   modifiers are not present in the C90 standard, but are present in the C99 standard.

An example of a format string is

The above format string scans the first seven characters as a decimal integer, then reads the remaining as a string until a space, new line or tab is found, then scans the first non-whitespace character following and a double-precision floating-point number afterwards.

Error handling
is usually used in situations when the program cannot guarantee that the input is in the expected format. Therefore a robust program must check whether the  call succeeded and take appropriate action. If the input was not in the correct format, the erroneous data will still be on the input stream and must be read and discarded before new input can be read. An alternative method of reading input, which avoids this, is to use  and then examine the string read in. The last step can be done by, for example.

Security
Like,   is vulnerable to format string attacks. Great care should be taken to ensure that the formatting string includes limitations for string and array sizes. In most cases the input string size from a user is arbitrary; it can not be determined before the  function is executed. This means that uses of  placeholders without length specifiers are inherently insecure and exploitable for buffer overflows. Another potential problem is to allow dynamic formatting strings, for example formatting strings stored in configuration files or other user controlled files. In this case the allowed input length of string sizes can not be specified unless the formatting string is checked beforehand and limitations are enforced. Related to this are additional or mismatched formatting placeholders which do not match the actual vararg list. These placeholders might be partially extracted from the stack, contain undesirable or even insecure pointers depending on the particular implementation of varargs.

/*Another use that works only on some special compilers is:

scanf("Please enter a value %d",&n);

Which prints the string in quotes and stops to accept input at the indicated %signs.*/

setvbuf
is a function in standard C which lets the programmer control the buffering of a file stream. It is declared in <stdio.h>; its function prototype is:

The stream argument is a pointer to the file stream for which the relevant buffering operations will be performed; buf is a character array of size in length, or a null pointer; and mode is the kind of buffering desired:, for fully buffered,   for line buffered and   for unbuffered. These three macros are defined in <stdio.h>. returns zero on success or nonzero on failure.

If buf is a null pointer, the system will dynamically allocate a buffer of the specified size (size characters). If mode is, the stream I/O will not be buffered, causing each subsequent I/O operation on the stream to be performed immediately, and the buf and size arguments are ignored.

A related function,  also controls the buffering of a file stream. Unlike,   takes only two arguments. The prototype is:

's behavior is equivalent to:

That is, if buf is not, set the stream to fully buffered using the given buffer; otherwise, set the stream to unbuffered. If a buffer is provided to, it must be at least   bytes long. The function always succeeds.

The code below is very unstable and might not work properly on specific compilers. It may even buffer overflow.. C99 says that setvbuf may not be called after writing to the stream, so this code invokes undefined behavior. C99 footnote 230 (non-normative) says the stream should be closed before buf is deallocated at the end of main.

Example
The output of this program should be Hello world followed by a newline.

tmpfile
In computing,  is an ISO C/POSIX function for creating a temporary file, a computer file which ceases to exist when the program, which opened the file, closes it or terminates.

Inclusion

 * C
 * C++

Semantics
The function  reports a pointer to a valid file stream on success; on failure, it returns.

Error conditions
In addition to returning,   sets   on failure. The permissible values of, if   fails, are:
 * - if a signal was caught during the execution of tmpfile.
 * - if the maximum number of file descriptors and/or the maximum number of file streams has been reached (in the process).
 * - if the maximum allowable number of files is currently open (in the system).
 * - if there is no space in the file system for creating the temporary file.
 * - if the file is a regular file and the size of the file cannot be represented correctly in an object of type off_t.
 * - if there is insufficient memory for allocating the file stream.

Caveats
The  function is susceptible to a number of security vulnerabilities; use the non-portable   (UNIX) or   (MSVCRT) functions, instead, to avoid these issues.

The implementation of this function in Microsoft C run-time library tries to create the file in the root directory of the current drive and typically fails reporting "Access denied".

ungetc
Ungetc is a version of a C standard library function ungetch. It is somewhat a restricted function.

Declaration
Here, c is a character variable, stream is a file pointer and the overall function is expressed in integer data type.

Description
As mentioned above, rather it is a restricted version of ungetch, the function pushes the character specified by the value of c. At the time of pushing, the character c is converted to a unsigned char and then pushed to the input stream. The pushed character can be returned if a getc function is applied to the stream.

Calling capacity
A single push back of the character is allowed at a call. Trying to do a push back in a succession may or may not work properly. In normal and usual practices, 4 times the function is called and hence 4 characters are pushed consecutively. It means that the process of this function is totally machine dependent. Hence if memory is large in extent in a machine then there is a possibility to have the push backs for infinitly large times.

Return value
The characters which are pushed back are returned by any subsequent read on the stream (in reverse order) and if the input from the stream is buffered, it means that the  last character pushed will be returned first. When a normal push back of the character is done, the function returns the last pushed character. If the push back operation is not done properly means if the push back of a character is unsuccessful (e.g. if the file is not open) then EOF character is returned as an error. One can not push back the EOF character to the stream using ungetc. A successful call to ungetc function clears the EOF indicator for the stream.

To erase the push back characters came from call to ungetc function, a call to fseek, fsetpos or fflush functions is made before the character is read from the stream. As all the characters are pushed back are read in, the file position indicator is same as before pushing back the characters.

Ungetc, a restricted version of ungetch
As stated already it is a restricted version of function ungetch, it has same restrictions like when a read operation is immediately folllowed by a write operation or vice versa. That is why, there is a requirement of a intervening reposition between ungetc and the subsequent write or read function.

vwprintf
<tt>vwprintf</tt> is a C standard library function as defined in wchar.h .It has function signature as int vwprintf(const wchar t *format, va_list args);

In signature of function vwprintf, format is format specialisation and args is pointer to arguments.

comparison with other functions
The functioning of vwprintf is same as that of swprintf. The difference between both functions is that the argument list has been replaced by a pointer to a list of argument. vwprintf performs the wide character output to the string like stdout and stdout should not be byte oriented.

The functioning of vwprintf is same as that of swprintf.The difference between both functions is that the argument list has been replaced by a pointer to a list of argument. vwprintf performs the wide character output to the string like stdout and stdout should not be byte oriented. this function return the number of characters not including the null character and any negative value if an output error occurs vwprintf is equivalent to wprintf with argument list replaced by arg and which can be initialised by vastart macro.

return values
vwprintf returns number of characters written but excluding the NULL character on success.But on failure it returns an error and errno is set.

wprintf
<tt>wprintf</tt> is a C standard library function as defined in wchar.h. It has function signature as  int wprintf(const wchar t *format,...); The wprintf writes output to stdout, the standard output stream. It uses variable argument lists. This function and also functions like vprintf, vfprintf, vsprintf, vsnprintf, and vasprintf offer the ability for programmers to essentially create their own printf variants.

Usage
The  function is found in C, in which writes the output to the stream under control of format strings. the format string specifies how subsequent arguments are converted for output.

wprintf is a wide character version of printf format. The format is a wide character string where wprintf and printf behave similarly as they are opened in ANSI mode.

Example
Following is the sample code for understanding of working of the wprintf.

code: After running the code output will be as follows: @TAJMAHAL@#$$$

Limitations
limitations:

1. wprintf is not portable function.

2. wprintf cannot be mixed with printf.

3. wprintf cannot print the double values. for e.g. 2^56 is the double value which cannot be printed using wprintf.

wscanf
wscanf

wscanf is a standard C library function in C programming language. It transforms wide character input. This function is supported by the header file wchar.h. wscanf is wide character version of scanf.

Syntax It returns count of inputs which are properly formatted. Count may be zero or less than the entered inputs in case of unformatted wide character input.

example

Now if the given input is like as given below: 83 56.6 k m Scanf input 54 22.3 a f Wscanf input

then output will be like this: The number of fields input is 6 The contents are: 83 56.599998 k m Scanf input The number of fields input is 6 The contents are: 54 22.300003 a f Wscanf input Thus scanf returns no of fields which are properly formatted or in another words which are successfully assigned.it does not does not returns the count for the field which is not properly formatted and such values are read but not assigned. And EOF is returned if end of the file character is encountered in first character reading of the file.