Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

fprintf — C23 stream function

`fprintf(stream, format, ...)` writes formatted data to the specified stream and returns the number of characters written, or a negative value on an encoding or output failure. Every conversion in `format` must match the actual argument type.

Version: C23

Syntax

int fprintf(FILE * restrict stream, const char * restrict format, ...);

fprintf(stream, format, ...) writes formatted data to the specified stream and returns the number of characters written, or a negative value on an encoding or output failure. Every conversion in format must match the actual argument type.

The example writes item=7 price=2.50 to a tmpfile(), rewinds it, and reads the result. Output 17 item=7 price=2.50 demonstrates the exact returned count and data produced by %d and %.2f.

A mismatched type, missing argument, or invalid pointer for %s/%n causes undefined behavior. Never use external text as the format; pass it through %s. Check a negative result and the stream error state, and remember that * field widths and precisions are supplied as int.

Examples

#include <stdio.h>
int main(void){FILE*s=tmpfile();if(!s)return 1;int n=fprintf(s,"item=%d price=%.2f",7,2.5);rewind(s);char b[32];if(!fgets(b,sizeof b,s)){fclose(s);return 1;}printf("%d %s\n",n,b);return fclose(s)==0?0:1;}

Result

17 item=7 price=2.50

The example writes `item=7 price=2.50` to a `tmpfile()`, rewinds it, and reads the result. Output `17 item=7 price=2.50` demonstrates the exact returned count and data produced by `%d` and `%.2f`.

Sources