C fputc() function
C library function - fputc()
The fputc() function is used to write the byte specified by c to the output stream pointed to by stream, at the position indicated by the associated file-position indicator for the stream (if defined), and shall advance the indicator appropriately.
Syntax:
int fputc(int c, FILE *stream)
Parameters:
Name | Description | Required /Optional |
---|---|---|
c | This is the character to be written. This is passed as its int promotion. | Required |
stream | Identifies an address for a file descriptor, which is an area of memory associated with an input or output stream. | Required |
Return value
- Upon successful completion, fputc() shall return the value it has written.
- Otherwise, it shall return EOF, the error indicator for the stream shall be set, and errno shall be set to indicate the error.
Example: fputc() function
#include <stdio.h>
int main () {
FILE *fp;
int ch;
char string[100];
fp = fopen("test.txt", "w+");
for( ch = 65 ; ch <= 122; ch++ ) {
fputc(ch, fp);
}
fclose(fp);
fp=fopen("test.txt","r");
fgets(string,100,fp);
printf("The string is:\n%s",string);
fclose(fp);
return 0;
}
Output:
The string is: ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz
Example: Write the contents of buffer to a file
#include <stdio.h>
#define ALPHA 6
int main(void)
{
FILE * fp;
int i;
int ch;
char string[6];
char buffer[ALPHA + 1] = "aeiou";
if (( fp = fopen("test.txt", "w"))!= NULL )
{
/* Put buffer into file */
for ( i = 0; ( i < sizeof(buffer) ) &&
((ch = fputc( buffer[i], fp)) != EOF ); ++i );
fclose(fp);
}
else
perror( "Error opening test.txt" );
fp=fopen("test.txt","r");
fgets(string,6,fp);
printf("The string is: %s",string);
fclose(fp);
return 0;
}
Output:
The string is: aeiou
C Programming Code Editor:
Previous C Programming: C fgets()
Next C Programming: C fputs()
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/c-programming/stdio/c_library_method_fputc.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics