putc C Library Function

The function int putc(int character, FILE *stream); writes a character to the given stream and increment the internal position indicator by one.

Function prototype of putc

int putc(int character, FILE *stream);
  • character : This is the character to be written on stream.
  • stream : A pointer to a FILE object which identifies a stream.

Return value of putc

This function returns the character written in stream, on success. If an error occurs, EOF is returned and the error indicator is set.

C program using putc function

The following program shows the use of putc and getc function to write and read characters in a stream respectively. The following program writes a string(one character at time using putc) in a new file and again prints it's content on screen using getc.

#include <stdio.h>
#include <string.h>

int main (){
   FILE *file;
   char *string = "putc C Standard Library function";
   int c, counter, length = strlen(string);

   file = fopen("textFile.txt", "w+");
   for(counter = 0; counter<length; counter++){
      putc(string[counter], file);
   /* Reset file pointer location to first character */
   /* Read characters from file */
      c = getc(file);
      printf("%c", c);

putc C Standard Library function

The following program shows the use of putc function to write a characters on a standard output stream stdout.

#include <stdio.h>

int main (){
    int c;
    printf("Enter a character\n");
    scanf("%c", &c);
    printf("You entered : ");
    putc(c, stdout);

Enter a character
You entered : A