fprintf() Write formatted output to a stream
fprintf() Write formatted output to a stream
fprintf() applies printf() formatting to a writable stream and returns the character count. Match types; check flushing and fclose() for delayed errors.
| Category | stdio.h I/O |
|---|---|
| Kind | Library function |
| Header | <stdio.h> |
| C standard | C89 / C90 |
📝 Syntax
int fprintf(FILE *stream, const char *format, ...);
⚙️ Parameters
| stream Required | An open stream available for output. |
|---|---|
| format Required | A format string controlling literal text and argument conversions. |
| ... Optional | Variable arguments supplied according to the conversion specifiers. |
Returns: Returns the number of characters written, excluding the terminating null character, or a negative value if an output or encoding error occurs.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Score 95
⚠️ Warning The stream must support output, and every conversion specifier must match its argument type. A stream opened read-only cannot be written.
💡 Tip The example uses tmpfile(), which creates a temporary file that is removed automatically, so it does not depend on an existing file.
🏷️ Related stdio.h functions
📚 Related Tutorials
❓ FAQ
QHow do I print an error message to stderr with fprintf?
APass stderr as the first argument, for example fprintf(stderr, "Error: %s\n", message). This keeps diagnostics separate from normal stdout output.
QWhy can't I immediately read data after writing it with fprintf?
AOutput may still be buffered, and an update stream has rules for switching between writing and reading. Use fflush() where appropriate and position the stream with fseek() or rewind() before reading.
QCan fprintf use user input directly as its format string?
ANo. A % in untrusted text may be interpreted as a conversion specifier, causing argument-type mismatches, disclosing sensitive data, or even performing an invalid write through %n. To print user text, use a fixed %s format with input as a separate argument, and ensure input is null-terminated.