The putc
function in C writes a character to any output stream and returns an integer value. It is a standard function in C and can be used by including the <stdio.h>
header file.
int putc(int ch, FILE *stream)
int
: The integer representation of the character to be written to the output stream.
stream
: A file stream or standard output stream identified by a pointer to the FILE object.
int
: Integer casting of the character written by putc
.If the write operation is unsuccessful due to an error or the end of a file is reached, EOF
is returned.
#include <stdio.h>int main() {char c;int ret;c = 'g';ret = putc(c, stdout); //ret stores the integer representation of the characterreturn 0;}
In the above code, the value g
stored in the character variable c
is displayed on standard output by the putc
function and the corresponding integer value 103
is stored in the variable ret
.
#include <stdio.h>int main() {char c;FILE *fp = fopen("new.txt","w");c = 'A';putc(c, fp);fclose(fp);//to test whether putc was successfulFILE *fp2 = fopen("new.txt","r");printf("%c", getc(fp));return 0;}
In this example, the text file new.txt
opens in write mode and is assigned to a file pointer fp
. The content of variable c
i.e., A
, is written at the position pointed to fp
in the file using the putc
function.
To test whether the write was successful to the file, it should be opened in read mode, and a character read using the
getc
function. The character read is then displayed on standard output.
Free Resources