C Library Function - putc()
C Standard Library - <stdio.h>
Description
The C library function int putc(int char, FILE *stream) writes the character specified by the argument char (an unsigned character) to the specified stream and advances the position indicator for the stream.
Declaration
Here is the declaration for the putc() function.
int putc(int char, FILE *stream)
Parameters
char -- This is the character to be written. The character is passed as its corresponding int value.
stream -- This is a pointer to a FILE object that identifies the stream to which the character is to be written.
Return Value
The function returns the character written as an unsigned char cast to an int, or EOF if an error occurs.
Example
The following example demonstrates the use of the putc() function.
#include <stdio.h>
int main ()
{
FILE *fp;
int ch;
fp = fopen("file.txt", "w");
for( ch = 33 ; ch <= 100; ch++ )
{
putc(ch, fp);
}
fclose(fp);
return(0);
}
Let's compile and run the above program, which will create a file file.txt in the current directory with the following content:
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd
Now, let's use the following program to view the content of the above file:
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}