fputc()
is used to write a single character to a file at the location indicated by the file pointer. After writing the character to the file, fputc()
increments the file pointer by one location. Below is the declaration of the fputc()
function:
int fputc (int character, FILE * stream);
The fputc()
function returns the character that is written if the character is successfully written to the file.
fputc()
functioncharacter
: Character to be written.stream
: Pointer to the file where the character is to be written.Consider the code snippet below, which uses fputc()
to write a character to a file:
#include <stdio.h>int main() {FILE * fPointer;char character;fPointer = fopen ("fputcExample.txt", "w");//opening filefputc('a', fPointer);//writing 'a' to filefputc('b', fPointer);//writing 'b' to filefclose(fPointer);return 0;}
The fopen()
function is used in line 8 to open the file for writing. The fputc()
function is used in line 10 to write character ‘a’ to the file location pointer with fPointer
. After successfully writing the ‘a’ character to the file, fputc()
increments the fPointer
by one location. This way, once the next write operation is applied to the file, the data is placed after the ‘a’ character written by fputc()
.
Once the code above is executed, the contents of fputcExample.txt
will be:
# fputcExample.txt
ab
Free Resources