C Programming/stdio.h/Function reference

clearerr.
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. codice_1 has the following prototype:
It takes one argument: a pointer to the "FILE" structure of the stream to close, eg:
codice_3
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:
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.
 #include &lt;stdio.h&gt;
 int main(void) 
 FILE *file_pointer;
 int i;
 file_pointer = fopen("myfile.txt", "r");
 fscanf(file_pointer, "%d", &amp;i);
 printf("The integer is %d\n", i);
 fclose(file_pointer);
 return 0;
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 codice_4 ("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 codice_6 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. 
Example code.
 #include &lt;stdio.h&gt;
 int main()
 FILE *fp = fopen("file.txt", "r");
 int c;
 c = getc(fp);
 while (c != EOF) {
 /* Echo the file to stdout */
 putchar(c);
 c = getc(fp);
 if (feof(fp))
 puts("End of file was reached.");
 else if (ferror(fp))
 puts("There was an error reading from the stream.");
 else
 /*NOTREACHED*/
 puts("getc() failed in a non-conforming way.");
 fclose(fp);
 return 0;
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.
fgetc.
Prototype.
 int fgetc(FILE *stream)
Description.
The fgetc function in the C standard library codice_7 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:
fgetpos.
fgetpos is a function in the I/O section of the C standard library.
Usage.
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, ftell() 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 errno 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. codice_8 stands for "file get string". It is included in the C standard library header file codice_7. The prototype of the function is as follows:
char* fgets(char *string, int length, FILE * stream);
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. codice_10 is commonly used here, for reading from the standard input. Otherwise, a codice_11 value returned by the codice_12 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.
int main(void)
 char str_buf[MAX_LEN + 1]; // One extra byte needed
 // for the null character
 while(fgets(str_buf, sizeof str_buf, stdin) != NULL)
 puts(str_buf);
 return 0;
Use in POSIX utilities.
For compliance with POSIX utility line lengths, the definition codice_13 (generally found in limits.h) is often used to size the character buffer.
Limitations.
The fixed buffer size imposed by codice_14 is cumbersome in applications which need to handle arbitrarily long lines of text. 
POSIX.1-2008-conforming systems provide a function called codice_15 (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 codice_16, 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 codice_17 performs the same operation after first closing any open stream associated with its parameters.
They are defined as
FILE *fopen(const char *path, const char *mode);
FILE *freopen(const char *path, const char *mode, FILE *fp);
The codice_16 function is essentially a slightly higher-level wrapper for the codice_19 system call of Unix operating systems. In the same way, codice_1 is often a thin wrapper for the Unix system call codice_21, and the C codice_6 structure itself often corresponds to a Unix file descriptor. In POSIX environments, the codice_23 function can be used to initialize a codice_6 structure from a file descriptor; however, file descriptors are a purely Unix concept not present in standard C.
The codice_25 parameter to codice_16 and codice_17 must be a string that begins with one of the following sequences:
The "b" 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 ( '+' 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 codice_28 or to a file positioning function (codice_29, codice_30, or codice_31), 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, codice_16 will return codice_33.
Glibc/musl notes.
Musl and Glibc support the e mode on Linux, which sets O_CLOEXEC on the new file descriptor. O_CLOEXEC 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. codice_34 stands for "file put string". It is included in the C standard library header file codice_7.
The function codice_34 terminates after reaching terminating null character (codice_37). The null character is not copied to the stream. The prototype of the function is as follows:
int fputs ( const char * str, FILE * stream );
The stream argument specifies the stream to which the string will be written. codice_38 is commonly used here, for writing to the standard output. Otherwise, a codice_11 value returned by the codice_12 function is used.
Sample usage.
The following example is 'hello world' program using codice_34:
int main() {
 const char *buffer = "Hello world!";
 fputs (buffer, stdout);
 return 0;
The following is a program that asks the user for his name and then writes it out:
int main() {
 char name[50];
 fputs("What is your name? ", stdout);
 fgets(name, sizeof(name), stdin);
 fputs(name, stdout);
 return 0;
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 codice_43 function copies codice_44 items of data of size codice_45 from the named input codice_46 into an array pointed to by codice_47. An item of data is a sequence of bytes (not necessarily terminated by a null byte) of length codice_45. codice_43 stops appending bytes when codice_44 items have been read, end of file has been reached, or an error has occurred. Upon returning, codice_43 sets the file pointer in the stream pointing to the byte past the last byte that has been read. The contents of codice_46 remain unchanged. The codice_43 function returns the number of items actually read. If codice_44 is zero, no action is taken and the function will return 0. 
Diagnostics.
The function may fail with the following error codes: 
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:
Return value.
The return value is an "integer" which mean:
Note that each error number has a distinct meaning. The meaning can be revealed by checking "errno.h".
Example.
int main(int argc, char **argv) {
 FILE *file_handle;
 long int file_length;
 file_handle = fopen("file.bin","rb");
 if(fseek(file_handle, 0, SEEK_END)) {
 puts("Error while seeking to end of file");
 return 1;
 file_length = ftell(file_handle);
 if (file_length &lt; 0) {
 puts("Error while reading file position");
 return 2;
 
 printf("File length: %d bytes\n", file_length);
 fclose(file_handle);
 return 0;
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. 
 long ftell ( FILE * stream );
fwprintf.
"fwprintf" 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 codice_43 and codice_57 functions respectively provide the file operations of input and output. codice_43 and codice_57 are declared in codice_60. It usually wraps write system call.
Writing a file using fwrite.
fwrite is defined as
codice_57 function writes a block of data to the stream. It will write an array of codice_63 elements to the current position in the stream. For each element, it will write codice_45 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 codice_63 if the write completes successfully. In case of a write error, the return value will be less than codice_63.
Example.
The following program opens a file named sample.txt, writes an array of characters to the file, and closes it. 
 #include &lt;stdio.h&gt;
 int main(void)
 FILE *file_ptr;
 int iCount;
 char arr[6] = "hello";
 file_ptr = fopen("sample.txt", "wb");
 iCount = fwrite(arr, 1, 5, file_ptr);
 fclose(file_ptr);
 return 0;
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*/
&lt;Source lang="c"&gt;
int main()
FILE *fp;
int c;
int n = 0;
fp = fopen("myfile.txt", "r");
 if(fp == NULL)
 perror ("Error opening file");
 else
 do {
 c = getc(fp);
 if(c == '#')
 n++;
 while(c != EOF);
 fclose(fp);
 printf ("File contains %d#.\n",n);
 return 0;
&lt;/syntaxhighlight&gt;
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.
Usage.
Declaration.
void perror(const char* prefix);
Example.
int fd = open("/etc/passwd", O_RDONLY);
if (fd == -1) {
 perror("open");
 exit(1); 
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 codice_67 function, to output a formatted string. It originated from the C programming language, where it has a prototype similar to the following:
 int printf(const char *format, ...)
The string constant codice_68 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 codice_69 statement references a non-executable codice_70 statement.
 PRINT 601, 123456, 1000.0, 3.1415, 250
 601 FORMAT (8H RED NUM I7,4H EXP,E8.1, ' REAL' F5.2,'; VALUE=',I4)
will print the following ( after advancing to a new line, because of the leading blank character if directed to a printing device):
 RED NUM 123456 EXP 1.0E 03 REAL 3.14; VALUE= 250
COBOL provides formatting via hierarchical data structure specification:
 01 out-rec.
 02 out-name picture x(20).
 02 out-amount picture $9,999.99.
 move me to out-name.
 move amount to out-amount.
 write out-rec.
1960s: BCPL, ALGOL 68, Multics PL/I.
C's variadic codice_67 has its origins in BCPL's codice_72 function.
ALGOL 68 Draft and Final report had the functions codice_73 and codice_74, subsequently these were revised out of the original language and replaced with the now more familiar codice_75 and codice_76.
 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 codice_77 with a wide variety of control codes. It was based on a machine-language facility from Multics's BOS (Bootstrap Operating System).
 call ioa_ ("Hello, ^a", "World!");
1970s: C, Lisp.
 printf("Color %s, number1 %d, number2 %05d, hex %x, float %5.2f, unsigned value %u.\n",
 "red", 123456, 89, 255, 3.14159, 250);
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 codice_67 function returns the number of characters printed, or a negative value if an output error occurs.
Common Lisp has the codice_68 function.
 (format t "Hello, ~a" "World!")
prints codice_80 on the standard output stream. If the first argument is codice_81, format returns the string to its caller. The first argument can also be any output stream. codice_68 was introduced into ZetaLisp at MIT in 1978, based on the Multics codice_77, and was later adopted into the Common Lisp standard.
1980s: Perl, Shell.
Perl also has a codice_67 function. Common Lisp has a format function which acts according to the same principles as codice_67, but uses different characters for output conversion. The GLib library contains codice_86, an implementation of codice_67.
Some Unix systems have a codice_67 program for use in shell scripts. This can be used instead of echo in situations where the latter is not portable. For example:
 echo -n -e "$FOO\t$BAR"
may be rewritten portably as:
 printf "%s\t%s" "$FOO" "$BAR"
1990s: PHP, Python.
1991: Python's codice_89 operator harkens to codice_67's syntax when interpolating the contents of a tuple. This operator can, for example, be used with the codice_91 function:
print("%s\t%s" % (foo,bar))
Version 2.6 of Python included the codice_92 which is preferred to the obsolete codice_89 which may go away in future versions of Python:
print("If you multiply five and six you get {0}.".format(5*6))
1995: PHP also has the codice_67 function, with the same specifications and usage as that in C/C++. MATLAB does not have codice_67, but does have its two extensions codice_96 and codice_97 which use the same formatting strings. codice_96 returns a formatted string instead of producing a visual output.
2000s: Java.
2004: Java supported codice_67 from version 1.5 onwards as a member of the codice_100 class, giving it the functionality of both the codice_67 and fprintf functions. At the same time codice_96-like functionality was added to the codice_103 class by adding the codice_104 method.
// Write "Hello, World!" to standard output (like printf)
System.out.printf("%s, %s", "Hello", "World!"); 
// create a String object with the value "Hello, World!" (like sprintf)
String myString = String.format("%s, %s", "Hello", "World!"); 
Unlike most other implementations, Java's implementation of codice_67 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.
 int fprintf(FILE *stream, const char *format, ...)
codice_97 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 codice_16 (or codice_23) function.
sprintf.
 int sprintf (char *str, const char *format, ...)
codice_96 prints to a string (codice_110 array) instead of standard output. Users of codice_96 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 codice_96 function does not have the codice_113 argument. Instead, it returns the formatted output string. The prototype in PHP is like this:
string sprintf (const string format, ...)
Buffer safety and sprintf.
In ISO C99, codice_114 was introduced as an alternative to codice_96 that can help avoid the risk of a buffer overflow:
 int snprintf(char *str, size_t size, const char * restrict format, ...)
codice_114 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:
char buf[BUFFER_SIZE];
int n;
n = snprintf(buf, BUFFER_SIZE, "Your name is %s.\n", username);
if (n &lt; 0 || n &gt;= BUFFER_SIZE)
 /* Handle error */
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 codice_114 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 codice_114 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 codice_114 harder than it should be.
Another safe codice_96 alternative is codice_121 which is a GNU extension:
 int asprintf(char **ret, const char *format, ...)
codice_121 automatically allocates enough memory to hold the final string. It sets codice_123 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 codice_123 to NULL on error). The programmer using codice_121 has the responsibility of freeing the allocated memory after use. Though not part of any standard, codice_121 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: codice_127, which allocates enough memory, but, unlike codice_121, 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 codice_96 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:
vprintf, vfprintf, vsprintf, vsnprintf, and vasprintf.
/* va_list versions of above */
int vprintf(const char *format, va_list ap);
int vfprintf(FILE *stream, const char *format, va_list ap);
int vsprintf(char *str, const char *format, va_list ap);
int vsnprintf(char *str, size_t size, const char *format, va_list ap);
int vasprintf(char **ret, const char *format, va_list ap);
These are analogous to the above functions without the "v"s, 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
 void fatal_error(const char *format, ...)
which would use the codice_130 macro to obtain a codice_131 variable from the extra parameters, print a message on the standard error device using codice_132, clean up after the codice_131 variable with the codice_134 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:
 int graphical_printf(int x, int y, const char *format, ...)
This would work by temporarily saving the string to a private buffer using codice_135 or codice_136.
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
Additionally, several platform-specific length options came to exist prior to widespread use of the ISO C99 extensions:
ISO C99 includes the codice_138 header file that includes a number of macros for use in platform-independent codice_67 coding. Example macros include:
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 codice_140 will result in codice_141 being printed, with a total width of 5 characters, and codice_142 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 codice_143 or codice_144). 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 "codice_145" 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 "codice_146" 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 codice_67-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 codice_148. 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 codice_67-like function, and embed extensions into it. However these all tend to have the same problems that codice_148 has.
Most non-C languages that have a codice_67-like function work around the lack of this feature by just using the "codice_152" format and converting the object to a string representation. C++ offers a notable exception, in that it has a codice_67 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.
codice_154 is equivalent to codice_155 and also expects a stream as parameter, but codice_154 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.
int putc ( int character, FILE * stream );
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 */
&lt;Source lang="c"&gt;
int main ()
 FILE *fp;
 char c;
 fp = fopen("alphabet.txt", "wt");
 for (c = 'A' ; c &lt;= 'Z' ; c++)
 putc (c , fp);
 fclose (fp);
 return 0;
&lt;/syntaxhighlight&gt;
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 codice_158 function is specified in the C standard library header file stdio.h.
Sample usage.
The following program uses codice_159 to read characters into an array and print them out using the codice_158 function after an end-of-file character is found.
 #include &lt;stdio.h&gt;
 int main(void)
 char str[1000];
 int ch, i, n = 0;
 while ((ch = getchar()) != EOF &amp;&amp; n &lt; 1000)
 str[n++] = ch;
 for (i = 0; i &lt; n; ++i)
 putchar(str[i]);
 putchar('\n'); /* trailing '\n' needed in Standard C */
 return 0;
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.
codice_161 is a function used to output a string (plus a newline), for example,
int main() {
 puts("welcome to WIKIPEDIA!!!");
"output (on stdout):"
 welcome to WIKIPEDIA!!!
Differences from printf:
1. codice_161 prints a newline after the supplied text
2. codice_161 prints the string as is (it does not process % codes).
We can also pass a variable to codice_161, for example,
int main() {
 const char *str = "welcome to WIKIPEDIA!!!";
 puts(str);
"output:"
 welcome to WIKIPEDIA!!!
codice_161 has the following prototype:
 int puts(const char *str)
It will print each byte at codice_113 until a null is reached, then print a newline. codice_161 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:
 printf("%s", "welcome to WIKIPEDIA!!!");
remove.
remove is a function in C programming language that removes a certain file. It is included in the C standard library header file codice_7.
The prototype of the function is as follows:
int remove ( const char * filename );
If successful, the function returns zero. Nonzero value is returned on failure and codice_169 variable is set to corresponding error code.
Sample usage.
The following program demonstrates common usage of codice_170:
int main() 
 const char *filename = "a.txt";
 remove (filename);
 return 0;
To implement a simple remove utility:
int main(char* argv[], int argc) 
 if (argc &gt; 1) {
 return remove (argv[1]);
 }else{
 return -1;
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 codice_169 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 codice_173 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 codice_7 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.
codice_31 acts as if codice_176 was called for the stream passed, except that codice_31 causes the error indicator to also be cleared.
Syntax.
void rewind( FILE *stream );
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 codice_178 function prototype is:&lt;br&gt;
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 codice_178 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:
int
main(void)
 int n;
 while (scanf("%d", &amp; n))
 printf("%d\n", n);
 return 0;
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:
int
main(void)
 char word[20];
 if(scanf("%19s", word) == 1)
 puts(word);
 return 0;
No matter what the datatype the programmer wants the program to read, the arguments (such as codice_180 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 codice_178 is designated to read only from standard input, many programming languages with interfaces, such as PHP, have derivatives such as codice_182 and codice_183 but not codice_178 itself.
Derivatives.
Depending on the actual source of input, programmers can use different derivatives of codice_178. Two common examples are codice_182 and codice_183.
fscanf.
The fscanf derivative reads input from a specified file stream. The prototypes are as follows:
(C or C++)&lt;br&gt;
int fscanf (FILE *file, const char *format, ...); 
(PHP)&lt;br&gt;
mixed fscanf (resource file, const string format [, mixed args...])
The codice_183 derivative works like the original codice_178 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++)&lt;br&gt;
int sscanf (const char *str, const char *format, ...); 
(PHP)&lt;br&gt;
mixed sscanf (const string str, const string format [, mixed args...])
vscanf, vsscanf, and vfscanf.
int vscanf (const char *format, va_list args);
int vsscanf (const char *source, const char *format, va_list args);
int vfscanf (FILE *file, const char *format, va_list args);
These are like the same functions without the codice_190 prefix, except they take their arguments from a codice_131. (See stdarg.h.) These variants may be used in variable-argument functions.
Format string specifications.
The formatting placeholders in codice_178 are more or less the same as that in codice_67, 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:
The above can be used in compound with numeric modifiers and the codice_227, codice_228 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 codice_229 modifiers if any, that specifies the number of characters to be scanned. An optional asterisk (codice_230) 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 codice_231 modifier in printf is not present in scanf, causing differences between modes of input and output. The codice_232 and codice_205 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.
codice_178 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 codice_178 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 codice_8 and then examine the string read in. The last step can be done by codice_182, for example.
Security.
Like codice_67, codice_178 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 codice_178 function is executed. This means that uses of codice_152 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",&amp;n);
Which prints the string in quotes and stops to accept input at the indicated %signs.*/
setvbuf.
codice_243 is a function in standard C which lets the programmer control the buffering of a file stream. It is declared in &lt;stdio.h&gt;; its function prototype is:
int setvbuf(FILE *stream, char *buf, int mode, size_t size);
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: codice_244, for fully buffered, codice_245 for line buffered and codice_246 for unbuffered. These three macros are defined in &lt;stdio.h&gt;. codice_243 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 codice_246, 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, codice_249 also controls the buffering of a file stream. Unlike codice_243, codice_249 takes only two arguments. The prototype is:
void setbuf(FILE *stream, char *buf);
codice_249's behavior is equivalent to:
(void)setvbuf(stream, buf, buf ? _IOFBF : _IONBF, BUFSIZ);
That is, if "buf" is not codice_33, set the stream to fully buffered using the given buffer; otherwise, set the stream to unbuffered. If a buffer is provided to codice_249, it must be at least codice_255 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.
int main(void) {
 char buf[42];
 if(setvbuf(stdout, buf, _IOFBF, sizeof buf)) {
 perror("failed to change the buffer of stdout");
 return EXIT_FAILURE;
 printf("He");
 /* The buffer contains "He"; nothing is written yet to stdout */
 fflush(stdout); /* "He" is actually written to stdout */
 if(setvbuf(stdout, NULL, _IONBF, 0)) {
 perror("failed to change the buffer of stdout");
 return EXIT_FAILURE;
 printf("llo w"); /* "llo w" is written to stdout, there is no buffering */
 if(setvbuf(stdout, buf, _IOLBF, sizeof buf)) {
 perror("failed to change the buffer of stdout");
 return EXIT_FAILURE;
 printf("orld"); /* The buffer now contains "orld"; nothing is written yet to stdout */
 putchar('\n'); /* stdout is line buffered; everything in the buffer is now written to stdout along with the newline */
 return EXIT_SUCCESS;
tmpfile.
In computing, codice_256 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.
Usage.
Inclusion.
codice_257
codice_258
Declaration.
codice_259
Semantics.
The function codice_256 reports a pointer to a valid file stream on success; on failure, it returns codice_33.
Error conditions.
In addition to returning codice_33, codice_256 sets codice_169 on failure. The permissible values of codice_169, if codice_256 fails, are:
Caveats.
The codice_256 function is susceptible to a number of security vulnerabilities; use the non-portable codice_274 (UNIX) or codice_275 (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.
codice_276
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.
"vwprintf" 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.
"wprintf" 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 codice_277 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:
int main(int argc,char *argv[])
 wchar_t *str = L"@TAJMAHAL@#$$$";
 wprintf(L"%ls\n", str);
 return EXIT_SUCCESS;
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.&lt;br&gt;
It transforms wide character input. This function is supported by the header file wchar.h. wscanf is wide character version of scanf.
&lt;/br&gt;Syntax&lt;/br&gt;
codice_278&lt;/br&gt;
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.
&lt;/br&gt;example
&lt;Source lang="c"&gt;
int main()
 int j, result;
 float a;
 char ch, string[128];
 wchar_t wch, wst[128];
 result = scanf( "%d %f %c %C %80s %80S", &amp;j, &amp;a, &amp;ch, &amp;wch, string, wst );
 printf( "The number of fields input is %d\n", result );
 printf( "The contents are: %d %f %c %C %s %S\n", j, a, ch, wch, string, wst);
 result = wscanf( L"%d %f %hc %lc %80S %80ls", &amp;j, &amp;a, &amp;ch, &amp;wch, string, wst );
 wprintf( L"The number of fields input is %d\n", result );
 wprintf( L"The contents are: %d %f %C %c %hs %s\n", j, a, ch, wch, string, wst);
 return 0;
}&lt;/syntaxhighlight&gt;
&lt;/br&gt;Now if the given input is like as given below:
83 56.6 k m Scanf input&lt;/br&gt;
54 22.3 a f Wscanf input
&lt;/br&gt;then output will be like this:&lt;/br&gt;
The number of fields input is 6&lt;/br&gt;
The contents are: 83 56.599998 k m Scanf input&lt;/br&gt;
The number of fields input is 6&lt;/br&gt;
The contents are: 54 22.300003 a f Wscanf input&lt;/br&gt;
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.