
- C Library - Home
- C Library - <assert.h>
- C Library - <complex.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <fenv.h>
- C Library - <float.h>
- C Library - <inttypes.h>
- C Library - <iso646.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdalign.h>
- C Library - <stdarg.h>
- C Library - <stdbool.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <tgmath.h>
- C Library - <time.h>
- C Library - <wctype.h>
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
C Library - putc() function
The C library putc() function writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream.
Syntax
Following is the C library syntax of putc() function −
int putc(int char, FILE *stream);
Parameters
This function accepts following paramters −
-
char: This is the character to be written. It is passed as an int, but it is internally converted to an unsigned char.
-
stream: This is a pointer to a FILE object that identifies the stream where the character is to be written. The stream can be any output stream such as a file opened in write mode, or standard output.
Return Value
The putc() function returns the character written as an unsigned char cast to an int on success. If there is an error, it returns EOF and sets the appropriate error indicator for the stream.
Example 1
Writing a Character to a File
This example opens a file in write mode and writes the character 'A' to it.
#include <stdio.h> int main() { FILE *file = fopen("example1.txt", "w"); if (file == NULL) { perror("Error opening file"); return 1; } putc('A', file); fclose(file); return 0; }
Output
The above code will create a file named example1.txt with the character 'A' written to it.−
A
Example 2
Writing Characters to a File with Error Handling
This example demonstrates error handling by checking the return value of putc() and printing an error message if writing fails.
#include <stdio.h> int main() { FILE *file = fopen("example3.txt", "w"); if (file == NULL) { perror("Error opening file"); return 1; } if (putc('B', file) == EOF) { perror("Error writing to file"); fclose(file); return 1; } fclose(file); return 0; }
Output
After execution of above code, a file named example3.txt will be created with the character 'B' written to it. If an error occurs during writing, an error message will be displayed.
B