← All languages
C function of the day
Random

putc

Write a character to a stream.

Description

The putc() function writes the character c, cast to unsigned char, to the given output stream. It advances the file position indicator for the stream after each write. putc() is functionally equivalent to fputc(), but it may be implemented as a macro that evaluates its arguments more than once.

Because putc() may be a macro, the stream argument should not be an expression with side effects. If this is a concern, use fputc() instead. On success, putc() returns the character written; on error, it returns EOF and sets the error indicator for the stream.

putc() is declared in <stdio.h> and is commonly used for writing files one character at a time. It can be paired with getc() to implement simple character-by-character file copying or transformation pipelines.

Arguments

NameDescriptionOptional
c The character to write, passed as an int. No
stream Pointer to a FILE object identifying the output stream. No

Example

FILE *fp = fopen("output.txt", "w");
if (fp == NULL) { perror("fopen"); return 1; }
const char *msg = "Hello";
for (int i = 0; msg[i] != '\0'; i++) {
    putc(msg[i], fp);
}
fclose(fp);

Reference