C Programming/stdio.h/putc

From Wikibooks, open books for an open world
Jump to navigation Jump to search

putc is the function in stdio.h. It is simplest way to write the file once it is open. It writes the character to stream and advances the position indicator. It is output function. The character is written at the current position of the stream as indicated by the internal position indicator, which is then advanced one character.

putc is equivalent to fputc and also expects a stream as parameter, but putc may be implemented as a macro, so the argument passed should not be an expression with potential side effects.

See putchar for a similar function without stream parameter.

int putc ( int character, FILE * stream );

Parameters[edit | edit source]

character
Character to be written. The character is passed as its int promotion.
stream
Pointer to a FILE object that identifies the stream where the character is to be written.

Return value[edit | edit source]

If there are no errors, the same character that has been written is returned. If an error occurs, EOF is returned and the error indicator is set.


Example[edit | edit source]

/* putc example: alphabet writer */ <Source lang="c">

  1. include <stdio.h>

int main () {

 FILE *fp;
 char c;
 fp = fopen("alphabet.txt", "wt");
 for (c = 'A' ; c <= 'Z' ; c++)
   {
    putc (c , fp);
   }
 fclose (fp);
 return 0;

} </syntaxhighlight>

Output[edit | edit source]

This example program creates a file called alphabet.txt and writes ABCDEFGHIJKLMNOPQRSTUVWXYZ to it.

Reference[edit | edit source]