Name

putc

Synopsis

Writes a character to a file

#include <stdio.h>
intputc( int c, FILE *fp );

The macro putc() is similar to the function fputc(). It writes one character to the current file position of the specified FILE pointer. The return value is the character written, or EOF if an error occurred.

Because putc() is a macro, it may evaluate its argument more than once. Make sure the argument is not an expression with side effects—or else use fputc()

Example

This is a simple search-and-replace filter to eliminate back-tick characters in text files:

int c;
FILE *fp;

if (( fp = fopen( "textfile", "r+" )) == NULL )
{
  fprintf( stderr, "Couldn't open input file.\n" );
  exit(-1);
}

while (( c = getc( fp )) != EOF ) // Read a character until EOF
{
  if ( c == '`' )              // If it's a back-tick ...
  {
    fseek( fp, -1, SEEK_CUR ); // back up to the place it was read from, andputc( '\'', fp );          // replace it with a single-quote character.
    fflush( fp );
  }
}
fclose( fp );

See Also

fgetc(), fputc(), getc(), getchar(), putchar(); the functions to read and write wide characters, putwc(), fputwc(), and putwchar(); getwc(), fgetwc(), and getwchar()

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.