Fprintf
Jump to navigation
Jump to search
Syntax
int fprintf ( FILE * stream, const char * format, ... );
Description
Write formatted data to stream
Writes the C string pointed by format to the stream. If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers.
After the format parameter, the function expects at least as many additional arguments as specified by format.
Parameters
- stream
- Pointer to a FILE object that identifies an output stream.
- format
- C string that contains the text to be written to the stream.
- It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested.
- A format specifier follows this prototype:
- %[flags][width][.precision][length]specifier
- Refer to printf for format
- ... (additional arguments)
- Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n).
- There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.
Return Value
On success, the total number of characters written is returned.
If a writing error occurs, the error indicator (ferror) is set and a negative number is returned.
If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned.
Example
Source | Run |
---|---|
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *pFile = NULL;
char favoritePet[20] = {0};
int numPets = 0;
pFile = fopen("pets", "w");
if (pFile != NULL)
{
printf("How many pets do you have? ");
scanf("%d", &numPets);
printf("Do you prefer cats or dogs? ");
scanf("%20s", favoritePet);
fprintf(pFile, "You have %d pets and prefer %s.\n", numPets, favoritePet);
fclose(pFile);
}
return 0;
}
|
$ ./code How many pets do you have? 3 Do you prefer cats or dogs? cats $ cat pets You have 3 pets and prefer cats. |