乐闻世界logo
搜索文章和话题

Difference between fprintf, printf and sprintf?

1个答案

1

fprintf, printf, and sprintf are all functions in C used for outputting formatted text, but they differ in usage scenarios and output destinations.

  1. printf

    • The printf function is the most commonly used output function, writing the formatted string to the standard output device, typically the terminal.
    • Example:
      c
      printf("Age: %d years\n", 25);
      This line of code displays "Age: 25 years" on the screen.
  2. fprintf

    • fprintf is very similar to printf but provides greater flexibility by allowing specification of an output stream (e.g., a file or other device) for output.
    • Example:
      c
      FILE *fp = fopen("output.txt", "w"); if (fp != NULL) { fprintf(fp, "Name: %s\n", "Zhang San"); fclose(fp); }
      This code writes "Name: Zhang San" to the output.txt file.
  3. sprintf

    • The sprintf function does not output data to the screen or file; instead, it stores the formatted string into a specified character array.
    • Example:
      c
      char buffer[50]; sprintf(buffer, "Weight: %d kilograms", 60); printf("%s\n", buffer);
      Here, sprintf stores the formatted string "Weight: 60 kilograms" into the buffer array, and then printf outputs this string.

In summary, the choice among these three functions depends on your specific needs, such as whether you need to redirect output to a file or other device, or whether you need to store the formatted string in a character array.

2024年6月29日 12:07 回复

你的答案