putc in c – putc : library function

putc in c: 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.

putc : <stdio.h> library function

#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 */
   rewind(file);
   /* Read characters from file */
   while(!feof(file)){
      c = getc(file);
      printf("%c", c);
   }
   fclose(file);
    
   return(0);
}

Output

putc C Standard Library function

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

C program using putc function

#include <stdio.h>
 
int main (){
    int c;
    printf("Enter a character\n");
    scanf("%c", &c);
     
    printf("You entered : ");
    putc(c, stdout);
     
    getch();
    return(0);
}

Output

Enter a character
A
You entered : A