Join our newsletter for the latest updates.

C++ putc()

The putc() function in C++ writes a character to the given output stream.

putc() prototype

int putc(int ch, FILE* stream);

The putc() function takes a output file stream and an integer as its arguments. The integer is converted to unsigned char and written to the file.

putc() and fputc() are similar in terms of functionality. However, a major difference between fputc() and putc() is that putc() can be implemented as a macro.

It is defined in <cstdio> header file.

putc() Parameters

  • ch: The character to be written.
  • stream: The file stream to write the character.

putc() Return value

  • On success, the putc() function returns the written character.
  • On failure, it returns EOF and sets the error indicator on stream.

Example: How putc() function works

#include <cstdio>
#include <cstring>

int main()
    char str[] = "Testing putc() function";
    FILE *fp;
    fp = fopen("file.txt","w");
    if (fp)
        for(int i=0; i<strlen(str); i++)
        perror("File opening failed");
    return 0;

When you run the program, the string "Testing putc() function" will be written to file.txt file.