What is fprintf Formatted File Output- C Programming Training Institute In Hyderabad

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course | Files | Lecture 16

fprintf Formatted File Output

Write numbers, text and structure fields to files with fprintf in C. Tested examples, format specifier tables and embedded C programming tips.

You already know printf from the first lectures of this free C programming course. fprintf in C is the same function with one extra argument at the front: the stream that receives the output. That single change turns every screen message into a file record, a log line or an error report. For embedded C programming, fprintf is how host tools and Linux-based devices produce readable measurement logs, CSV files and diagnostic reports.

In this lecture of our free C tutorial we write formatted data into files, check the return value, send output to stdout and stderr, and design a record layout that another program can read back. That last point is important, because the next lecture reads the same file with fscanf.

What You Will Learn

  • The declaration of fprintf and what it returns.
  • How fprintf differs from printf, sprintf and fputs.
  • How to write structure fields as one text line per record.
  • The format specifiers you will use every day, with width and precision.
  • Why a record needs separators and a newline if you want to read it later.
  • Safety, performance and code-size points for embedded targets.

Prerequisites

  • printf and its conversion specifiers (%d, %f, %s, %c).
  • fopen, fclose and the “w” and “a” file modes.
  • Structures in C, covered in the Structure and Union chapter.

How fprintf in C Works

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

The function reads the format string from left to right. Ordinary characters are copied to the stream as they are. Each % conversion takes the next argument, converts it to text and writes that text. The return value is the number of characters written, or a negative number if an error happened. Some books say it returns EOF on error; the standard only promises a negative value, so test with < 0.

From program variables to characters in a file

int 36, int 4, “A7” → format: TEMP=%d.%d C node=%s\n → text bytes → temp.log

Your First fprintf Program

#include <stdio.h>

int main(void)
{
    int whole = 36, frac = 4;
    FILE *fp = fopen("temp.log", "w");

    if (fp == NULL) {
        perror("fopen");
        return 1;
    }

    int n = fprintf(fp, "TEMP=%d.%d C node=%s\n", whole, frac, "A7");
    if (n < 0) {
        perror("fprintf");
        fclose(fp);
        return 1;
    }
    printf("fprintf wrote %d characters\n", n);

    fprintf(stdout, "same as printf: %d\n", 42);
    fprintf(stderr, "this goes to stderr\n");

    fclose(fp);
    return 0;
}

Build and run

$ gcc -Wall -Wextra -o ep_fprintf_log ep_fprintf_log.c
$ ./ep_fprintf_log
fprintf wrote 20 characters
same as printf: 42
this goes to stderr
$ cat temp.log
TEMP=36.4 C node=A7

Count it by hand: “TEMP=36.4” is 9 characters, then a space, the letter C, a space and “node=A7” (7 characters) make 19, and the newline makes 20. The return value matches exactly. Notice also that fprintf(stdout, …) behaves like printf, because printf(x) is just fprintf(stdout, x).

Stream order on a pipe: stdout is line-buffered on a terminal but fully buffered when redirected, while stderr is unbuffered. If you redirect both to a file, lines may appear in a different order than the code suggests. Call fflush(stdout) when order matters.

Writing Structure Records With fprintf

Now a more realistic job: store a table of measurements. Each structure becomes one line, with a space between the fields and a newline at the end. This is the layout rule that makes the file readable by humans and by fscanf.

#include <stdio.h>

struct reading {
    char  tag[12];
    float volts;
};

int main(void)
{
    struct reading r[] = {
        { "ADC0", 3.30f },
        { "ADC1", 1.65f },
        { "VBAT", 4.02f },
    };
    FILE *fp = fopen("readings.txt", "w");

    if (fp == NULL) {
        perror("fopen");
        return 1;
    }

    for (size_t i = 0; i < sizeof r / sizeof r[0]; i++)
        fprintf(fp, "%s %.2f\n", r[i].tag, r[i].volts);

    fclose(fp);
    return 0;
}
$ gcc -Wall -Wextra -o ep_fprintf_records ep_fprintf_records.c
$ ./ep_fprintf_records
$ cat readings.txt
ADC0 3.30
ADC1 1.65
VBAT 4.02

Why separators and newlines are not optional

Imagine writing “%s%f” with no space and no newline. Three records would become ADC03.300000ADC11.650000VBAT4.020000, one unbroken string. No program could split it back into names and numbers. Always end a record with a newline and put a space, comma or tab between fields.

Format Specifiers You Will Use Every Day

SpecifierMeaningExample callOutput
%dsigned intfprintf(fp, “%d”, -5)-5
%uunsigned intfprintf(fp, “%u”, 300u)300
%xhexadecimalfprintf(fp, “%x”, 255)ff
%cone characterfprintf(fp, “%c”, ‘A’)A
%sstringfprintf(fp, “%s”, “uart”)uart
%.2ffloat, 2 decimalsfprintf(fp, “%.2f”, 3.3)3.30
%5dright-aligned, width 5fprintf(fp, “%5d”, 42)   42
%-6sleft-aligned, width 6fprintf(fp, “%-6s|”, “ab”)ab    |
%zusize_t valuefprintf(fp, “%zu”, sizeof(int))4

Without a precision, %f prints six digits after the decimal point, so 3.30 would be stored as 3.300000. Choose the precision your data really has.

fprintf vs printf vs sprintf vs fputs

FunctionOutput goes toBest used for
printfstdoutMessages on the console
fprintfAny FILE streamFiles, stderr, formatted logs
sprintf / snprintfA char arrayBuilding strings in memory
fputsAny FILE streamPlain strings with no formatting

Real-World Use in Embedded C Programming

  • CSV logs from a data-acquisition tool: timestamp, channel, value on every line.
  • Error reports written to stderr so that scripts can separate them from normal output.
  • Generated header or configuration files created by a host-side build helper.
  • Test vectors for a signal-processing routine, saved as readable text for review.

Common Mistakes and Troubleshooting

MistakeEffectFix
Wrong specifier, such as %d for a floatGarbage numbers, compiler warningCompile with -Wall and read the warnings
Missing newline between recordsRecords merge into one lineEnd every record format with \n
No separator between fieldsFile cannot be parsed backUse a space, comma or tab
Names containing spaces with a space separatorReader splits the nameUse a comma or tab separator, or no spaces in names
Passing a NULL string to %sCrash or the text (null)Check pointers before printing
File not closedLast lines missing on diskfclose, or fflush after key lines

Best Practices, Performance and Security

  • Security: never use data from outside your program as the format string. Write fprintf(fp, "%s", text), not fprintf(fp, text).
  • Code size: floating-point formatting adds significant size to firmware. Some small C libraries, such as newlib-nano, leave it out unless you enable it with a linker option. Printing a scaled integer (for example 3300 millivolts) is an easy way to avoid floats.
  • Speed: fprintf parses the format at run time. For a fixed string use fputs, for large binary data use fwrite.
  • Check the return value in programs where losing a record matters, such as a disk-full condition.
  • Keep one record per line and document the field order so other tools can parse the file.

Key Takeaways and Conclusion

Summary

  • fprintf works like printf but writes to the stream you pass as the first argument.
  • It returns the number of characters written, or a negative value on error.
  • Design records with separators and a newline so they can be read back.
  • Use a precision such as %.2f to control how many digits are stored.
  • Never pass untrusted text as the format; use “%s” with the text as an argument.

fprintf in C turns your program data into readable files with a single call. You now have all three text-writing tools from this chapter: fputc for characters, fputs for strings and fprintf for formatted data. In the next lecture of this free embedded C course we do the reverse and read the readings.txt file back with fscanf, including what to do when a line is damaged.

Frequently Asked Questions

What is the difference between printf and fprintf?

printf always writes to stdout. fprintf takes a FILE pointer as its first argument, so it can write to a file, stderr or stdout.

What does fprintf return?

The number of characters written, or a negative number on error. In our test the line TEMP=36.4 C node=A7 plus newline returned 20.

How do I write a structure to a text file?

Print each member with the right specifier in one fprintf call, separate the fields with spaces or commas, and end with a newline so each structure is one line.

Why are my numbers written with six decimal places?

%f defaults to six digits after the point. Use %.2f or another precision to control the output.

How do I print to the error stream?

Use fprintf(stderr, …). stderr is unbuffered, so messages appear immediately.

Is fprintf safe with user input?

Only if the user input is an argument, not the format. Use fprintf(fp, “%s”, input) to avoid format string attacks.

Next: Reading It Back With fscanf

Continue this free C programming course with fscanf, a quiz and interview questions on file handling.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →