putc() – putchar() — Write a Character
Format
#include <stdio.h>
int putc(int c, FILE *stream);
int putchar(int c);
Language Level
ANSI
Threadsafe
No
#undef putc
or #undef putchar
allows
the putc
or putchar
function to
be called instead of the macro version of these functions. The functions
are threadsafe.
Description
The putc()
function
converts c to unsigned char and
then writes c to the output stream at
the current position. The putchar()
is
equivalent to putc(c, stdout)
.
The putc()
function
can be defined as a macro so the argument can be evaluated multiple
times.
The putc()
and putchar()
functions
are not supported for files opened with type=record.
Return Value
The putc()
and putchar()
functions
return the character written. A return value of EOF indicates
an error.
The value of errno may be set to:
- Value
- Meaning
- ECONVERT
- A conversion error occurred.
- EPUTANDGET
- An illegal write operation occurred after a read operation.
- EIOERROR
- A non-recoverable I/O error occurred.
- EIORECERR
- A recoverable I/O error occurred.
Example
This example writes the contents
of a buffer to a data stream. In this example, the body of the for statement
is null because the example carries out the writing operation in the
test expression.
#include <stdio.h>
#include <string.h>
#define LENGTH 80
int main(void)
{
FILE *stream = stdout;
int i, ch;
char buffer[LENGTH + 1] = "Hello world";
/* This could be replaced by using the fwrite function */
for ( i = 0;
(i < strlen(buffer)) && ((ch = putc(buffer[i], stream)) != EOF);
++i);
}
/******************** Expected output: **************************
Hello world
*/