C programming fputc stdio.h


In C programming the <stdio.h> fputc function writes the character to the specified stream.The stream here can be file or console.The declaration of the function is given below.

int fputc(int c, FILE *stream);

Parameters:
c -The characters to write to stream.

stream -The stream to which the the character ‘c’ is to be written.

Return type
int -Returns the character written.If a write error occurs,the error indicator for the stream is set and ‘fputc’ returns EOF.

Note the character is written at a position specified by the file position indicator which in newly created file is at the beginning or the position indicated by calling a position indicator function like ‘fsetpos’ or ‘rewind’. After writing the character to the stream the position indicator for the stream is incremented appropriately thus allowing the next character to be written to the next position.If the file does not support positioning the file indicator to a specified position or if the file is open with append mode then the character is appended to the stream.

A code exmple given below takes a character from a string and prints it out on the console using ‘fputc’.

Code example

char str[] = “New string” ;

unsigned int i = 0 ;

while (i < strlen( str ) )  //strlen is found in string.h header
{
fputc(str[i] , stdout);
i++;
}

Output

New string

In this example the stream passed as the first argument is ‘stdout’ which write the character to the console.Another program is given below which writes the character to a file.

Code example

FILE *fp=fopen(“text.txt” , “w”);

char str[] = “New string” ;

unsigned int i = 0 ;

while (i < strlen( str ) )  //strlen is found in string.h header
{
fputc(str[i] , fp);
i++;
}

fclose(fp)

After running the program if you open the file ‘text.txt’ found in the current directory where your main.c file is present,you will see your string “New string” written on it.


Related links

->C fputs stdio.h

->C fgetc stdio.h

->C putc stdio.h

->C fopen stdio.h

->C fclose stdio.h