C++ Standard Library C++ STL Library

C++ <cstdio> - fputc() Function



The C++ <cstdio> fputc() 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.

Syntax

int fputc ( 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 <cstdio>
 
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++)
    fputc(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++ <cstdio> Library