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.

Categorystdio.h I/O
KindLibrary function
Header<stdio.h>
C standardC89 / C90

📝 Syntax

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

⚙️ Parameters

stream RequiredAn open stream available for output.
format RequiredA format string controlling literal text and argument conversions.
... OptionalVariable 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏