CFile IoBeginner

fprintf()

Prints formatted output to a file stream.

Review the syntaxStudy the examplesOpen the coding app
fprintf(stream, "format", arguments...);

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Prints formatted output to a file stream.

fprintf() (File Print Formatted) is a standard C library function that sends formatted output to a specified stream, designated by a FILE pointer. It functions identically to printf(), but offers the flexibility to target files, standard error (stderr), or other custom streams. Technically, fprintf() uses a buffer provided by the C standard I/O library; data is often not flushed to the physical disk until the buffer is full, the file is closed, or fflush() is called. It returns the number of characters successfully written or a negative value upon failure. Developers must ensure the stream pointer is valid and open with write permissions, as passing a NULL pointer results in undefined behavior (typically a segmentation fault). Performance impacts can occur during frequent small writes due to I/O overhead, so batching or manual buffering with setvbuf() is sometimes preferred for high-throughput logging applications. It is also important to consider thread-safety; while POSIX guarantees atomic writes to streams, interleaving can occur if multiple threads call fprintf() on the same stream without external synchronization.

Quick reference

Syntax

fprintf(stream, "format", arguments...);

Inputs

Parameters

streamFILE* · Target stream (file, stderr, etc.).
formatconst char* · Format string with specifiers.
... (optional)variadic · Values to format and print.

See it in practice

Examples

1

Persistent Logging to a File

#include <stdio.h>

int main() {
    FILE *log_file = fopen("system.log", "a");
    if (log_file == NULL) return 1;

    const char *status = "SUCCESS";
    int code = 200;
    fprintf(log_file, "[LOG] Status: %s, Code: %d\n", status, code);

    fclose(log_file);
    return 0;
}
Output:
(system.log content) [LOG] Status: SUCCESS, Code: 200

Opens a file in append mode ('a') and writes a structured log entry. The function ensures that the data is directed to the file stream rather than the console.

2

Directing Errors to stderr

#include <stdio.h>

int main() {
    int error_id = 404;
    if (error_id != 0) {
        fprintf(stderr, "Critical Error: ID %d detected\n", error_id);
    }
    return 0;
}
Output:
Critical Error: ID 404 detected

Demonstrates writing to the standard error stream. This is a common practice to separate error messages from standard program output (stdout), allowing for cleaner pipe redirection in shells.

3

Generating a CSV Record

#include <stdio.h>

int main() {
    FILE *fp = fopen("users.csv", "w");
    if (!fp) return 1;

    int userId = 1052;
    float balance = 250.75;
    fprintf(fp, "UserID,Balance\n%d,%.2f\n", userId, balance);

    fclose(fp);
    return 0;
}
Output:
(users.csv content) UserID,Balance\n1052,250.75

Formats numeric data with specific precision (%.2f) and writes it into a file using a comma-separated format for interoperability with spreadsheet software.

Debug faster

Common Errors

1

LogicError

Cause: Passing a NULL FILE pointer to fprintf, which typically occurs when fopen() fails (e.g., file not found or permission denied) and the return value is not checked.

Fix: Always verify that the FILE pointer is not NULL before calling fprintf().

FILE *f = fopen("restricted.txt", "r");
fprintf(f, "Attempting write"); // Will crash if f is NULL
2

TypeError

Cause: Format specifier mismatch, where the variable type provided does not match the conversion specifier in the format string (e.g., passing an int to %s).

Fix: Ensure that the arguments passed to fprintf match the placeholders in the format string exactly.

int age = 30;
fprintf(stdout, "Age: %s", age); // Incorrect: %s expects char*, not int

Runtime support

Compatibility

C89+

stdio.h; standard across platforms

Source: MDN Web Docs

Common questions

Frequently Asked Questions

Prints formatted output to a file stream.

stream: Target stream (file, stderr, etc.). format: Format string with specifiers. ...: Values to format and print.

LogicError: Always verify that the FILE pointer is not NULL before calling fprintf(). TypeError: Ensure that the arguments passed to fprintf match the placeholders in the format string exactly.