
- 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 - fputc() function
The C library fputc(int char, FILE *stream) function writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream. This function is part of the standard I/O library, and it is commonly used when working with file operations in C programming.
Syntax
Following is the C library syntax of the fputc() function −
int fputc(int char, FILE *stream);
Parameters
This function accepts the following parameters −
- int char: The character to be written. Although it is an int, it represents an unsigned char cast to an int value.
- *FILE stream: A pointer to a FILE object that identifies the output stream. This stream is typically created using functions like fopen.
Return Value
On success, fputc returns the character written as an unsigned char cast to an int. On failure, it returns EOF (End of File) and sets the appropriate error indicator on the stream.
Example 1: Writing a Single Character to a File
This program opens a file named "example1.txt" in write mode and writes the character 'A' to it.
Below is the illustration of C library fputc() function.
#include <stdio.h> int main() { FILE *file = fopen("example1.txt", "w"); if (file == NULL) { perror("Failed to open file"); return 1; } fputc('A', file); fclose(file); return 0; }
Output
After execution of above code, the file "example1.txt" will contain the single character 'A'.
Example 2 : Writing multiple characters
This program will create a file file.txt in the current directory which will contain the characters with ASCI values from 33 to 100.
#include <stdio.h> int main () { FILE *fp; int ch; fp = fopen("file.txt", "w+"); for( ch = 33 ; ch <= 100; ch++ ) { fputc(ch, fp); } fclose(fp); return(0); }
Output
The above code produces following result−
!"#$%&'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd