fscanf
int fscanf ( FILE * stream , const char * format [ , argument , ...] ); | stdio.h |
cplusplus.com |
Read formatted data from a stream.
Reads data from the current position of stream and
stores it into the locations given by argument(s).
Locations pointed by each argument are filled with
their corresponding type of value requested
in the format string.
There must be the same number of
type specifiers in format string
than arguments passed.
Parameters.
%[*][width][modifiers]type
where:
* | Data is read but ignored. It is not assigned to the corresponding argument. |
width | Specifies the maximum number of characters to be read. |
modifiers | Specifies a different size for the data pointed by argument:
|
type | Character specifying the type of data that is expected and how it has to be read. See next table. |
*scanf types:
Qualifying Input | Argument required | |
Single character: Reads the next character (whitespace characters included). | char * | |
Decimal integer: Number optionally preceeded with a sign. | int * | |
Floating point: Decimal number containing a decimal point, optionally preceeded by a sign and optionally folowed by the e or E character and a decimal number. Valid entries are -732.103 or 7.12e4 | float * | |
Octal integer. | int * | |
String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are blank, newline and tab). | char * (string) | |
Unsigned decimal integer. | unsigned int * | |
Hexadecimal integer. | int * |
int n;
fscanf (stream,"%d",&n);
Return Value.
The number of items succesfully read. This count doesn't include any ignored fields.
If EOF is returned an error has occurred before the
first assignation could be done.
Portability.
Defined in ANSI-C.
Example.
/* fscanf example */
#include <stdio.h>
main ()
{
char str [80];
float f;
FILE * pFile;
pFile = fopen ("myfile.txt","w+");
fprintf (pFile, "%f %s", 3.1416, "PI");
rewind (pFile);
fscanf (pFile, "%f", &f);
fscanf (pFile, "%s", str);
fclose (pFile);
printf ("I have read: %f and %s \n",f,str);
return 0;
}
This sample code creates a file called myfile.txt
and stores a float number and a string, then, the stream is rewinded
and both values are read with fscanf. Finally
produces this output:
I have read: 3.141600 and PI
See also.
scanf,
fprintf,
fopen,
fclose