fscanf() in C with Examples

The fscanf() is a C Library function which reads formatted input from the stream. fscanf reads data from the file which is pointed by File Pointer. If you want to read data from the file which saved in a readable format then you can use this function.

Basic Syntax

Following is the basic syntax for fscanf() C library function wich is available by default.

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

And the parameters are as given below:

Parameter Description
stream Pointer to file object for identification of string.
format Format specifier present in [=%[*][width][modifiers]type=] format.

  • * = (Optional) Asterisks that shows that data is to be read from stream
  • width = The Maximum number of characters to be read
  • modifiers = Indicates size difference for data pointed by the corresponding argument.
  • type = Type of data is a character which indicates the type of data

Return Value

The fscanf() function returns all the input items matched and assigned with the given format.


Below is an example for fscanf() C Library function.

/*c program demonstrating fscanf and its usage*/
int main() 
    char name[20], gender[20];
    int rollno,age;
    /* demo.txt which contains following data 
       ROLLNO    NAME       AGE    GENDER 
       1         Ashwini    17     FEMALE
       2         Rutuja     18     FEMALE 
       3         Priyanka   17     FEMALE
       4         Abhijeet   19     MALE
    FILE* pointer = fopen("demo.txt","r"); 
    if (pointer == NULL) { 
        printf("No file found."); 
        return 0; 
    while (fscanf(pointer,"%d %s %d %s",&rollno,name,&age,gender) == 1 ){
        printf("%s\n", name); 
    return 0;

The output should be: