C Standard Library

C <stdio.h> - putc() Function



The C <stdio.h> putc() function writes a character ch to the output stream stream and advances the position indicator. Internally, the character is converted to unsigned char just before being written.

putc() and fputc() are equivalent, except that putc() may be implemented as a macro in some libraries.

Syntax

int putc ( int ch, FILE * stream );

Parameters

ch Specify a character to be written.
stream Specify a pointer to a FILE object that specifies an output stream.

Return Value

On success, the character ch is returned. On failure, returns EOF and sets the error indicator ferror().

Example:

In the example below, the file test.txt is opened in write mode.The program creates an empty file for output operations if the file does not exist. If the file already exists, its contents are discarded and the file is treated as a new empty file. Finally it writes ABCDEFGHIJKLMNOPQRSTUVWXYZ in the file before closing it.

#include <stdio.h>
 
int main (){
  //open the file in write mode
  FILE *pFile = fopen("test.txt", "w");
  
  //writes character in the file
  for(char ch = 'A'; ch <= 'Z'; ch++)
    putc(ch, pFile);

  //close the file
  fclose(pFile);
  
  //open the file in read mode to read
  //the content of the file
  pFile = fopen("test.txt", "r");
  int c = fgetc(pFile);
  while (c != EOF) {
    putchar(c);
    c = fgetc(pFile);
  }

  //close the file
  fclose(pFile);
  return 0;
}

The output of the above code will be:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

❮ C <stdio.h> Library

5