Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - fscanf()

C Library Function - fscanf()

C Standard Library - <stdio.h> C Standard Library -

Description

C Library Function **int fscanf(FILE stream, const char format, ...) Read formatted input from the stream stream.

Declaration

Below is the declaration of the fscanf() function.



int fscanf(FILE *stream, const char *format, ...)

Parameters

Parameters Description
* This is an optional asterisk indicating that data is read from the stream stream but is ignored, that is, it is not stored in the corresponding argument.
width This specifies the maximum number of characters to be read in the current operation.
modifiers : h: short int (for d, i, and n), or unsigned short int (for o, u, and x); l: long int (for d, i, and n), or unsigned long int (for o, u, and x), or double (for e, f, and g); L: long double (for e, f, and g).
type A character that specifies the type of data to be read and how it is read. See the next table for details.

fscanf type specifiers:

Type Valid input Argument type
c Single character: reads the next character. If a width other than 1 is specified, the function reads width characters and, passing them via the argument, stores them in consecutive positions of the array. No null character is appended at the end. char *
d Decimal integer: the + or - sign before the number is optional. int *
e,E,f,g,G Floating-point number: includes a decimal point, an optional leading + or - sign, an optional trailing e or E character, and a decimal number. Two valid examples are -732.103 and 7.12e4. float *
o Octal integer. int *
s String. This reads consecutive characters until a whitespace character is encountered (a whitespace character can be a space, newline, or tab). char *
u Unsigned decimal integer. unsigned int *
x,X Hexadecimal integer. int *

Return Value

If successful, the function returns the number of successfully matched and assigned items. If the end of the file is reached or a read error occurs, EOF is returned.

Example

The following example demonstrates the use of the fscanf() function.



#include 

#include 





int main()

{

   char str1[10], str2[10], str3[10];

   int year;

   FILE * fp;



   fp = fopen ("file.txt", "w+");

   fputs("We are in 2014", fp);

   

   rewind(fp);

   fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);

   

   printf("Read String1 |%s|\n", str1 );

   printf("Read String2 |%s|\n", str2 );

   printf("Read String3 |%s|\n", str3 );

   printf("Read Integer |%d|\n", year );



   fclose(fp);

   

   return(0);

}

Let's compile and run the above program, which will produce the following result:



Read String1 |We|

Read String2 |are|

Read String3 |in|

Read Integer |2014|

C Standard Library - <stdio.h> C Standard Library -