#include <stdio.h>
int printf (const char *format, ...);
int fprintf (FILE *stream, const char *format, ...);
int sprintf (char *str, const char *format, ...);
int snprintf (char *str, size_t size, const char *format, ...);
printf is the standard output function.
fprintf transfer format output to a file. Sends information (parameters) to the file specified by the stream (stream) according to the specified format (format), and fprintf only works like printf. If successful, the return value is the number of characters of the output, and returns a negative when an error occurs. The first parameter is the file pointer stream, and the following argument is the parameter in printf, whose function is to send the output to the file specified by the file pointer, and if you want to send the output to the standard output like printf, just specify the file pointer filename as stdout.
The sample program is as follows:
#include <stdio.h>
FILE *stream;
int
main (void)
{
char s[] = "This is a string.\n";
char c = ' \ n ';
stream = fopen ("Fprintf.out", "w");
fprintf (Stream, "%s", s);
fprintf (stdout, "abc\n");
return 0;
}
The result of this program is that the Fprintf.out file is stored in the this is a string. String, output the ABC string in standard output.
sprintf, the string Format command, the main function is to write formatted data into a string. The first parameter, STR, is a char pointer to a buffer for the string that will be written. The second argument that follows is a format string.
Sample programs:
#include <stdio.h>
int
main (void)
{
char s[100];
sprintf (S, "%%SFJDKSFJ");
printf ("%s\n", s);
return 0;
}
After execution the output result is
%sfjdksfj
The snprintf function is similar to the sprintf function. It also formats a variable parameter as a string in the format, and then copies it into Str.
(1) If the formatted string length < size, copy the string into str and add a string terminator (' ") toit,(2) If the formatted string length >= size, only the ( SIZE-1) character to Str, and adds a string terminator (' the ') followed by, returning the length of the formatted string.
Sample programs:
#include <stdio.h>
int
main (void)
{
char s[10];
snprintf (S, 4, "%%SFJDKSFJ");
printf ("%s\n", s);
snprintf (S, sizeof (s), "%%SFJDKSFJ");
printf ("%s\n", s);
return 0;
}
Run Result:
%sf
%SFJDKSFJ