C Programming/stdio.h/Function reference

From Wikibooks, open books for an open world
Jump to navigation Jump to search


[edit | edit source]


[edit | edit source]
void clearerr( FILE *stream );


[edit | edit source]

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.


[edit | edit source]

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. fclose has the following prototype:

int fclose(FILE *file_pointer)

It takes one argument: a pointer to the FILE structure of the stream to close, eg: :fclose(my_file_pointer) 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

[edit | edit source]
 #include <stdio.h>

 int main(void) 
   FILE *file_pointer;
   int i;
   file_pointer = fopen("myfile.txt", "r");
   fscanf(file_pointer, "%d", &i);
   printf("The integer is %d\n", i);
   return 0;

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

feof is a C standard library function declared in the header stdio.h.[1] Its primary purpose is to distinguish between cases where a stream operation has reached the end of a file and cases where the EOF ("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

[edit | edit source]

The function is declared as follows:

int feof(FILE *fp);

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

Return value

[edit | edit source]

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

[edit | edit source]
 #include <stdio.h>
 int main()
     FILE *fp = fopen("file.txt", "r");
     int c;
     c = getc(fp);
     while (c != EOF) {
         /* Echo the file to stdout */
         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.");
       puts("getc() failed in a non-conforming way.");
     return 0;


[edit | edit source]

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.


[edit | edit source]


[edit | edit source]
int fgetc(FILE *stream)


[edit | edit source]

The fgetc function in the C standard library stdio.h 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


[edit | edit source]

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


[edit | edit source]
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, 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).


[edit | edit source]

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.[2] fgets stands for file get string. It is included in the C standard library header file stdio.h. 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. stdin is commonly used here, for reading from the standard input. Otherwise, a FILE * value returned by the fopen() function is used.

Sample usage

[edit | edit source]

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.

#include <stdio.h>

#define MAX_LEN 20

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)

  return 0;

Use in POSIX utilities

[edit | edit source]

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


[edit | edit source]

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

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

Advanced applications can avoid buffer limitations by using mmap.


[edit | edit source]

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

Opening a file using fopen

[edit | edit source]

A file is opened using fopen, 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 freopen 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 fopen function is essentially a slightly higher-level wrapper for the open system call of Unix operating systems. In the same way, fclose is often a thin wrapper for the Unix system call close, and the C FILE structure itself often corresponds to a Unix file descriptor. In POSIX environments, the fdopen function can be used to initialize a FILE structure from a file descriptor; however, file descriptors are a purely Unix concept not present in standard C.

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

mode description starts..
r rb open for reading (The file must exist) beginning
w wb open for writing (creates file if it doesn't exist). Deletes content and overwrites the file. beginning
a ab open for appending (creates file if it doesn't exist) end
r+ rb+ r+b open for reading and writing (The file must exist) beginning
w+ wb+ w+b open for reading and writing. If file exists deletes content and overwrites the file, otherwise creates an empty new file beginning
a+ ab+ a+b open for reading and writing (append if file exists) end

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 fflush or to a file positioning function (fseek, fsetpos, or rewind), and reads cannot be followed by writes without an intervening call to a file positioning function.[5]

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, fopen will return NULL.

Glibc/musl notes

[edit | edit source]

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.


[edit | edit source]

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

The function fputs terminates after reaching terminating null character ('\0'). 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. stdout is commonly used here, for writing to the standard output. Otherwise, a FILE * value returned by the fopen() function is used.

Sample usage

[edit | edit source]

The following example is 'hello world' program using fputs:

#include <stdio.h>

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:

#include <stdio.h>
int main() {
    char name[50];
    fputs("What is your name? ", stdout);
    fgets(name, sizeof(name), stdin);
    fputs(name, stdout);
    return 0;


[edit | edit source]

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

size_t fread (void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream)

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


[edit | edit source]

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.


[edit | edit source]

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.


[edit | edit source]
int fseek(FILE *stream_pointer, long offset, int origin);

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

[edit | edit source]

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.


[edit | edit source]
#include <stdio.h>

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 < 0) {
    puts("Error while reading file position");
    return 2;
  printf("File length: %d bytes\n", file_length);
  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.


[edit | edit source]

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.


[edit | edit source]

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


[edit | edit source]

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 );


[edit | edit source]

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.


[edit | edit source]

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.


[edit | edit source]

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.


[edit | edit source]

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


[edit | edit source]

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

Writing a file using fwrite

[edit | edit source]

fwrite is defined as

int fwrite ( const void * array, size_t size, size_t count, FILE * stream );

fwrite function writes a block of data to the stream. It will write an array of count elements to the current position in the stream. For each element, it will write size 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 count if the write completes successfully. In case of a write error, the return value will be less than count.


[edit | edit source]

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

 #include <stdio.h>
 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);
     return 0;

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.


[edit | edit source]
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.


[edit | edit source]

/*getc example*/ <Source lang="c">

  1. include <stdio.h>

int main() { FILE *fp; int c; int n = 0; fp = fopen("myfile.txt", "r");

 if(fp == NULL)
    perror ("Error opening file");
    do  {
        c = getc(fp);
        if(c == '#')
    while(c != EOF);
 printf ("File contains %d#.\n",n);
return 0;


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

Return Value

[edit | edit source]

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.

[edit | edit source]


[edit | edit source]

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.[7]It prints str and an implementation-defined error message corresponding to the global variable errno.


[edit | edit source]

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


[edit | edit source]


[edit | edit source]
#include <stdio.h>


[edit | edit source]
void perror(const char* prefix);


[edit | edit source]
int fd = open("/etc/passwd", O_RDONLY);
if (fd == -1) {


[edit | edit source]

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


[edit | edit source]
An example of the printf function.

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.


[edit | edit source]

Many programming languages implement a printf 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 format 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

[edit | edit source]

Fortran's variadic PRINT statement references a non-executable FORMAT 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)[8]:

 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

[edit | edit source]

C's variadic printf has its origins in BCPL's writef function.

ALGOL 68 Draft and Final report had the functions inf and outf, subsequently these were revised out of the original language and replaced with the now more familiar readf/getf and printf/putf.

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 ioa_ 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

[edit | edit source]
 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 printf function returns the number of characters printed, or a negative value if an output error occurs.

Common Lisp has the format function.

 (format t "Hello, ~a" "World!")

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

1980s: Perl, Shell

[edit | edit source]

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

Some Unix systems have a printf 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

[edit | edit source]

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

print("%s\t%s" % (foo,bar))

Version 2.6 of Python included the str.format() which is preferred to the obsolete % 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 printf function, with the same specifications and usage as that in C/C++. MATLAB does not have printf, but does have its two extensions sprintf and fprintf which use the same formatting strings. sprintf returns a formatted string instead of producing a visual output.

2000s: Java

[edit | edit source]

2004: Java supported printf from version 1.5 onwards as a member of the PrintStream[9] class, giving it the functionality of both the printf and fprintf functions. At the same time sprintf-like functionality was added to the String class by adding the format(String, Object... args) method.[10]

// 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 printf throws an exception on encountering a malformed format string.

[edit | edit source]

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:


[edit | edit source]
int fprintf(FILE *stream, const char *format, ...)

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 fopen (or fdopen) function.


[edit | edit source]
int sprintf (char *str, const char *format, ...)

sprintf prints to a string (char array) instead of standard output. Users of sprintf 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 sprintf function does not have the str argument. Instead, it returns the formatted output string. The prototype in PHP is like this:

string sprintf (const string format, ...)

Buffer safety and sprintf

[edit | edit source]

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

int snprintf(char *str, size_t size, const char * restrict format, ...)

snprintf 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:

#define BUFFER_SIZE 50
char buf[BUFFER_SIZE];
int n;
n = snprintf(buf, BUFFER_SIZE, "Your name is %s.\n", username);
if (n < 0 || n >= 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 snprintf 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 snprintf 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 snprintf harder than it should be.

Another safe sprintf alternative is asprintf which is a GNU extension:

int asprintf(char **ret, const char *format, ...)

asprintf automatically allocates enough memory to hold the final string. It sets *ret 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 *ret to NULL on error). The programmer using asprintf has the responsibility of freeing the allocated memory after use. Though not part of any standard, asprintf 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: g_strdup_printf, which allocates enough memory, but, unlike asprintf, returns the resulting string as its return value rather than via the first argument.

C++ alternatives to sprintf for numeric conversion

[edit | edit source]

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 sprintf 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

[edit | edit source]
#include <stdio.h>
/* 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 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

void fatal_error(const char *format, ...)

which would use the va_start macro to obtain a va_list variable from the extra parameters, print a message on the standard error device using vfprintf, clean up after the va_list variable with the va_end 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 vsnprintf or vasprintf.

Format placeholders

[edit | edit source]

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:
Character Description
n$ 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: printf("%2$d %2$#x; %1$d %1$#x",16,17) produces

"17 0x11; 16 0x10"

  • Flags can be zero or more (in any order) of:
Character Description
Left-align the output of this placeholder (the default is to right-align the output).
Prepends a plus for positive signed-numeric types. positive = '+', negative = '-'. (the default doesn't prepend anything in front of positive numbers).
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).
Prepends zeros for numbers when the width option is specified. (the default prepends spaces).

Example: printf("%2d", 3) produces " 3", while printf("%02d", 3) produces in "03".

Alternate form. For 'g' and 'G', trailing zeros are not removed. For 'f', 'F', 'e', 'E', 'g', 'G', the output always contains a decimal point. For 'o', 'x', 'X', or '0', '0x', '0X', 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:
Character Description
hh For integer types, causes printf to expect an int sized integer argument which was promoted from a char.
h For integer types, causes printf to expect an int sized integer argument which was promoted from a short.
l For integer types, causes printf to expect a long sized integer argument.
ll For integer types, causes printf to expect a long long sized integer argument.
L For floating point types, causes printf to expect a long double argument.
z For integer types, causes printf to expect a size_t sized integer argument.
j For integer types, causes printf to expect a intmax_t sized integer argument.
t For integer types, causes printf to expect a ptrdiff_t sized integer argument.

Additionally, several platform-specific length options came to exist prior to widespread use of the ISO C99 extensions:

Characters Description
I For signed integer types, causes printf to expect ptrdiff_t sized integer argument; for unsigned integer types, causes printf to expect size_t sized integer argument. Commonly found in Win32/Win64 platforms.
I32 For integer types, causes printf to expect a 32-bit (double word) integer argument. Commonly found in Win32/Win64 platforms.
I64 For integer types, causes printf to expect a 64-bit (quad word) integer argument. Commonly found in Win32/Win64 platforms.
q For integer types, causes printf to expect a 64-bit (quad word) integer argument. Commonly found in BSD platforms.

ISO C99 includes the inttypes.h header file that includes a number of macros for use in platform-independent printf coding. Example macros include:

Characters Description
PRId32 Typically equivalent to I32d (Win32/Win64) or d
PRId64 Typically equivalent to I64d (Win32/Win64), lld (32-bit platforms) or ld (64-bit platforms)
PRIi32 Typically equivalent to I32i (Win32/Win64) or i
PRIi64 Typically equivalent to I64i (Win32/Win64), lli (32-bit platforms) or li (64-bit platforms)
PRIu32 Typically equivalent to I32u (Win32/Win64) or u
PRIu64 Typically equivalent to I64u (Win32/Win64), llu (32-bit platforms) or lu (64-bit platforms)
PRIx64 Typically equivalent to I64x (Win32/Win64), llx (32-bit platforms) or lx (64-bit platforms)
  • Type can be any of:
Character Description
d, i int as a signed decimal number. '%d' and '%i' are synonymous for output, but are different when used with scanf() for input.
u Print decimal unsigned int.
f, F double 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').
e, E double 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 _set_output_format function.
g, G double 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.
x, X unsigned int as a hexadecimal number. 'x' uses lower-case letters and 'X' uses upper-case.
o unsigned int in octal.
s null-terminated string.
c char (character).
p void * (pointer to void) in an implementation-defined format.
n 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).

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 printf("%*d", 5, 10) will result in "   10" being printed, with a total width of 5 characters, and printf("%.*s", 3, "abcdef") 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 -Wall or -Wformat). 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

[edit | edit source]

Using only field widths to provide for tabulation, as with a format like "%8d%8d%8d" 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 " %7d %7d %7d" 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

[edit | edit source]

There are a few implementations of printf-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 register_printf_function(). 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 printf-like function, and embed extensions into it. However these all tend to have the same problems that register_printf_function() has.

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

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.

putc is equivalent to fputc and also expects a stream as parameter, but putc 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 );


[edit | edit source]
Character to be written. The character is passed as its int promotion.
Pointer to a FILE object that identifies the stream where the character is to be written.

Return value

[edit | edit source]

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.


[edit | edit source]

/* putc example: alphabet writer */ <Source lang="c">

  1. include <stdio.h>

int main () {

 FILE *fp;
 char c;
 fp = fopen("alphabet.txt", "wt");
 for (c = 'A' ; c <= 'Z' ; c++)
    putc (c , fp);
 fclose (fp);
 return 0;

} </syntaxhighlight>


[edit | edit source]

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


[edit | edit source]

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

int putchar (int character)

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 putchar function is specified in the C standard library header file stdio.h.

Sample usage

[edit | edit source]

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

 #include <stdio.h>

 int main(void)
   char str[1000];
   int ch, i, n = 0;
   while ((ch = getchar()) != EOF && n < 1000)
     str[n++] = ch;
   for (i = 0; i < n; ++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 is a function used to output a string (plus a newline), for example,

#include <stdio.h>
int main() {
    puts("welcome to WIKIPEDIA!!!");

output (on stdout):

welcome to WIKIPEDIA!!!

Differences from printf:

1. puts prints a newline after the supplied text

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

We can also pass a variable to puts, for example,

#include <stdio.h>
int main() {
    const char *str = "welcome to WIKIPEDIA!!!";


welcome to WIKIPEDIA!!!

puts has the following prototype:

int puts(const char *str)

It will print each byte at str until a null is reached, then print a newline. puts 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!!!");


[edit | edit source]

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

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 errno variable is set to corresponding error code.

Sample usage

[edit | edit source]

The following program demonstrates common usage of remove:

#include <stdio.h>

int main() 
    const char *filename = "a.txt";
    remove (filename);
    return 0;

To implement a simple remove utility:

#include <stdio.h>

int main(char* argv[], int argc) 
    if (argc > 1) {
        return remove (argv[1]);
        return -1;


[edit | edit source]

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

The prototype of the function is:

int rename(const char *oldname, const char *newname)

Zero is returned upon success. Other integers are returned upon failure and errno 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 cstdio 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.[13] 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.


[edit | edit source]

rewind is a function in the C programming language that is specified in the stdio.h 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.[14]

rewind acts as if fseek(stream, 0L, SEEK_SET) was called for the stream passed, except that rewind causes the error indicator to also be cleared.


[edit | edit source]
#include <stdio.h>
void rewind( FILE *stream );


[edit | edit source]

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 scanf function prototype is:

int scanf(const char *format, ...);

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.


[edit | edit source]

The scanf 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:

#include <stdio.h>

    int n;
    while (scanf("%d", & 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

will appear neatly as:


To print out a word:

#include <stdio.h>

    char word[20];
    if(scanf("%19s", word) == 1)
    return 0;

No matter what the datatype the programmer wants the program to read, the arguments (such as &n 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 scanf is designated to read only from standard input, many programming languages with interfaces, such as PHP, have derivatives such as sscanf and fscanf but not scanf itself.


[edit | edit source]

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


[edit | edit source]

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

(C or C++)

int fscanf (FILE *file, const char *format, ...);


mixed fscanf (resource file, const string format [, mixed args...])

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


[edit | edit source]

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++)

int sscanf (const char *str, const char *format, ...);


mixed sscanf (const string str, const string format [, mixed args...])

vscanf, vsscanf, and vfscanf

[edit | edit source]
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 v prefix, except they take their arguments from a va_list. (See stdarg.h.) These variants may be used in variable-argument functions.

Format string specifications

[edit | edit source]

The formatting placeholders in scanf are more or less the same as that in printf, 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:

  • %d : Scan an integer as a signed decimal number.
  • %i : Scan an integer as a signed number. Similar to %d, but interprets the number as hexadecimal when preceded by 0x and octal when preceded by 0. For example, the string 031 would be read as 31 using %d, and 25 using %i. The flag h in %hi indicates conversion to a short and hh conversion to a char.
  • %u : Scan for decimal unsigned int (Note that in the C99 standard the input value minus sign is optional, so if a negative[clarification needed] number is read, no errors will arise and the result will be the two's complement. See strtoul().Template:Failed verification) Correspondingly, %hu scans for an unsigned short and %hhu for an unsigned char.
  • %f : Scan a floating-point number in normal (fixed-point) notation.
  • %g, %G : Scan a floating-point number in either normal or exponential notation. %g uses lower-case letters and %G uses upper-case.
  • %x, %X : Scan an integer as an unsigned hexadecimal number.
  • %o : Scan an integer as an octal number.
  • %s : 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.
  • %c : Scan a character (char). No null character is added.
  • (space): Space scans for whitespace characters.
  • %lf : Scan as a double floating-point number.
  • %Lf : Scan as a long double floating-point number.

The above can be used in compound with numeric modifiers and the l, L 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 long 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 ff modifier in printf is not present in scanf, causing differences between modes of input and output. The ll and hh modifiers are not present in the C90 standard, but are present in the C99 standard.[15]

An example of a format string is

"%7d%s %c%lf"

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

[edit | edit source]

scanf 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 scanf 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 fgets and then examine the string read in. The last step can be done by sscanf, for example.


[edit | edit source]

Like printf, scanf 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 scanf function is executed. This means that uses of %s 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.*/


[edit | edit source]

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:

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: _IOFBF, for fully buffered, _IOLBF for line buffered and _IONBF for unbuffered. These three macros are defined in <stdio.h>. setvbuf 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 _IONBF, 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, setbuf also controls the buffering of a file stream. Unlike setvbuf, setbuf takes only two arguments. The prototype is:

void setbuf(FILE *stream, char *buf);

setbuf's behavior is equivalent to:

(void)setvbuf(stream, buf, buf ? _IOFBF : _IONBF, BUFSIZ);

That is, if buf is not NULL, set the stream to fully buffered using the given buffer; otherwise, set the stream to unbuffered. If a buffer is provided to setbuf, it must be at least BUFSIZ 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.


[edit | edit source]

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

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char buf[42];

    if(setvbuf(stdout, buf, _IOFBF, sizeof buf)) {
        perror("failed to change the buffer of stdout");
        return EXIT_FAILURE;
    /* 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;


[edit | edit source]

In computing, tmpfile 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.[16][17][18]


[edit | edit source]


[edit | edit source]

#include <stdio.h>


#include <cstdio>


[edit | edit source]

FILE* tmpfile(void);


[edit | edit source]

The function tmpfile reports a pointer to a valid file stream on success; on failure, it returns NULL.[16]

Error conditions

[edit | edit source]

In addition to returning NULL, tmpfile sets errno on failure. The permissible values of errno, if tmpfile fails, are:[16]

  • EINTR - if a signal was caught during the execution of tmpfile.
  • EMFILE - if the maximum number of file descriptors and/or the maximum number of file streams has been reached (in the process).
  • ENFILE - if the maximum allowable number of files is currently open (in the system).
  • ENOSPC - if there is no space in the file system for creating the temporary file.
  • EOVERFLOW - if the file is a regular file and the size of the file cannot be represented correctly in an object of type off_t.
  • ENOMEM - if there is insufficient memory for allocating the file stream.


[edit | edit source]

The tmpfile function is susceptible to a number of security vulnerabilities; use the non-portable mkstemp (UNIX) or tmpfile_s (MSVCRT) functions, instead, to avoid these issues.[19][20]

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".


[edit | edit source]

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


[edit | edit source]

int ungetc (int c, FILE *stream)

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


[edit | edit source]

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

[edit | edit source]

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

[edit | edit source]

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

[edit | edit source]

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.


[edit | edit source]

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

[edit | edit source]

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

[edit | edit source]

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


[edit | edit source]

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.


[edit | edit source]

The wprintf 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.


[edit | edit source]

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


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:



[edit | edit source]

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().


[edit | edit source]


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.

int wscanf(const wchar_t[21]*input in formatted form)
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 <Source lang="c">

  1. include<stdio.h>

int main() {

  int   j, result;
  float a;
  char  ch, string[128];
  wchar_t wch, wst[128];
  result = scanf( "%d %f %c %C %80s %80S", &j, &a, &ch, &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", &j, &a, &ch, &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;


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.

  1. ISO/IEC 9899:1999 specification (PDF). p. 305, §
  2. ISO/IEC 9899:1999 specification (PDF). p. 296, §
  3. http://www.gnu.org/software/libc/manual/html_node/Line-Input.html#index-getline-993
  4. http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html
  5. http://www.opengroup.org/onlinepubs/009695399/functions/fopen.html
  6. ISO/IEC 9899:1999 specification (PDF). p. 301, §
  7. ISO/IEC 9899:1999 specification (PDF). p. 305, §
  8. "ASA Print Control Characters". Retrieved February 12, 2010.
  9. "PrintStream (Java 2 Platform SE 5.0)". Sun Microsystems Inc. 1994. Retrieved 2008-11-18.
  10. "String (Java 2 Platform SE 5.0)". Sun Microsystems Inc. 1994. Retrieved 2008-11-18.
  11. ISO/IEC 9899:1999 specification (PDF). p. 299, §
  12. ISO/IEC 9899:1999 specification (PDF). p. 268, §
  13. rename: rename a file – System Interfaces Reference, The Single UNIX® Specification, Issue 7 from The Open Group
  14. [1], The Open Group Base Specifications Issue 7, IEEE Std 1003.1-2008.
  15. C99 standard, § "The fscanf function" alinea 11.
  16. a b c tmpfile by OpenGroup
  17. Temporary Files by GNU C Library
  18. tmpfile by HMUG
  19. TMPNAM-TMPFILE Vulnerability by Build Security In
  20. VOID FI039-C. Create temporary files securely by CERT
  21. wchar_t