printf() vs fprintf() Functions in C – Key Differences

Get Certified in C Programming for Free and Take Your Skills to the Next Level

Outputting data is a fundamental task in C programming. The printf() and fprintf() functions are two primary methods for displaying program results and values. Choosing the right output tool is crucial based on your needs.

This article will dive deep into printf() and fprintf(), highlighting key differences in usage, capabilities, performance, and applications. Code examples will demonstrate real-world scenarios for each one. By the end, you’ll understand precisely when to use printf() or fprintf() for any programming situation.

Printf() Function in C

The printf() function outputs formatted text to the standard output stream (stdout). By default, it prints to the console window.

Syntax

int printf(const char *format, ...);

It takes a format string specifying how to print the values, along with a variable number of arguments containing the values to print. It returns the number of characters printed.

Format Specifiers

Commonly used format specifiers:

  • %d – print as decimal integer
  • %f – print as floating point
  • %s – print as a string
  • %c – print as character
  • %p – print a pointer address

Examples

Printing different data types:

int num = 10;
float gpa = 3.5;
char grade = 'A';


printf("Integer: %d\n", num); // Prints 10
printf("GPA: %f\n", gpa); // Prints 3.500000
printf("Grade: %c\n", grade); // Prints A

Printing a string:

char *name = "DataFlair";


printf("Name: %s\n", name); // Prints Name: DataFlair

Pros

  • Simple syntax for basic printing
  • Fast execution for console output
  • Output by default goes to stdout

Cons

  • Only prints to stdout, lacks file output support
  • Limited formatting options
  • No built-in error handling

printing a string

Fprintf() Function in C

The fprintf() function also outputs formatted text but to a specified stream. This allows printing of files, pipes, and more.

Syntax

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

The key difference vs printf() is the FILE* stream argument. This tells fprintf() where to direct the output.

File Streams

Some common file streams:

  • stdout – Standard output stream
  • stderr – Standard error stream
  • File pointer – From fopen(), points to file on disk

Examples

Printing to a file:

FILE *fp;
fp = fopen("output.txt", "w");


fprintf(fp, "Hello world!"); 


fclose(fp);

This prints “Hello world!” to output.txt instead of the console.

Printing to stderr:

fprintf(stderr, "Error: %s", errorMsg);

Prints error message to stderr stream.

Pros

  • Supports file output
  • More formatting options
  • Can return error codes

Cons

  • Slightly more complex syntax
  • File output has more overhead

Key Differences In-Depth

Featureprintf()fprintf()
Output DestinationBy default, it prints to the standard output (stdout), which is usually the console.Can print to any valid output stream specified by the file pointer argument, including stdout, files, pipes, etc.
Formatting CapabilitiesSupports basic formatting like %d for integers and %s for stringsHas additional formatting options for controlling field width, precision, and alignment when printing
Error HandlingNo direct error handling. Limited robustnessReturns error codes from I/O operations that can be checked directly in code
PerformanceVery fast and efficient for simple stdout printingSlower due to disk I/O when writing output to files
FlexibilitySimple and easy to use for basic console printingIt is more flexible since output can be directed to different destinations
Use CasesIdeal for simple program output, status messages, etcBetter for debugging, logging, writing output files, robust programs
Header File#include <stdio.h>#include <stdio.h>
Declarationint printf(const char *format, …);int fprintf(FILE *stream, const char *format, …);
Return ValueReturns the number of characters printedReturns the number of characters printed or negative number if an error

Recommended Usage Guidelines

Based on their technical differences, here are some general guidelines on when to use printf() vs. fprintf():

Use printf() when:

  • You just need quick console printing
  • Output speed is the top priority
  • You don’t need to write output to files

Use fprintf() when:

  • You need to print output to files
  • Error checking and robustness is important
  • Flexible formatting options are required

Neither is necessarily “better” – it depends on the specific program needs.

Performance Benchmark Comparison

To demonstrate the performance differences, here is a simple benchmark test comparing printf() and fprintf():

#include <stdio.h>
#include <time.h>


#define NUM_ITERS 1000000


int main() {


  clock_t t;
  int i; 
  FILE *fp;
  
  // printf() time test
  t = clock();
  for (i = 0; i < NUM_ITERS; i++) {
    printf("Hello World\n");
  }
  t = clock() - t;


  // fprintf() time test
  fp = fopen("output.txt", "w"); 


  t = clock();
  for (i = 0; i < NUM_ITERS; i++) {
    fprintf(fp, "Hello World\n");
  }
  t = clock() - t;
  
  fclose(fp);


  double printf_time = ((double)t)/CLOCKS_PER_SEC; 
  double fprintf_time = ((double)t)/CLOCKS_PER_SEC;


  printf("printf time: %f seconds\n", printf_time);
  printf("fprintf time: %f seconds\n", fprintf_time);


  return 0;
}

On my system, a sample run gave these results:
printf time: 0.097615 seconds
fprintf time: 2.393325 seconds

As expected, printf() was significantly faster due to lower overhead. But fprintf() provides that important file-writing capability.

Real-World Usage Scenarios

To tie it all together, here are some real-world examples that demonstrate good usage of printf() and fprintf():

Scenario 1 – Simple command line tool to print status

Since we just need quick stdout printing, printf() is best:

void printStatus(int code) {
  if (code == 0) {
    printf("Success!\n");
  }
  else {
    printf("Error code: %d\n", code); 
  }
}

Scenario 2 – Writing logs for a server

We need file output, so fprintf(logfile) makes sense:

void logMessage(char *msg) {
  fprintf(logfile, "%s: %s\n", currentTime(), msg); 
}

This demonstrates realistic use cases based on their specific needs.

Conclusion

printf() and fprintf() are versatile output functions with distinct advantages based on the programming situation. printf() is perfect for fast and simple console printing, while fprintf() enables file output and robust error handling. By understanding the key differences in output, formatting, speed, and use cases, you can decide which one fits your needs. With the power to direct output flexibly, C programmers can build robust systems and provide meaningful program results.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

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