Join our newsletter for the latest updates.

C++ fputc()

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

fputc() prototype

int fputc(int ch, FILE* stream);

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

It is defined in <cstdio> header file.

fputc() Parameters

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

fputc() Return value

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

Example: How fputc() function works

#include <cstdio>
#include <cstring>

int main()
    char str[] = "Hello programmers";
    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 "Hello programmers" will be written to file.txt file.