scanf() and fscanf() in C

Last Updated : 21 Jul, 2026

The scanf() and fscanf() functions are standard input functions in C used to read formatted data. While scanf() reads input from the standard input (stdin), fscanf() reads formatted input from a specified file.

  • scanf() is commonly used to accept input from the keyboard during program execution.
  • fscanf() is used to read structured data stored in files using a file pointer.

scanf()

The scanf() function is a standard library function declared in the <stdio.h> header file. It is used to read formatted input from the standard input (stdin) and store it in variables.

  • It reads input according to the specified format specifiers (such as %d, %f, %c, and %s).
  • It accepts one or more variable addresses where the input values will be stored.
  • On success, it returns the number of input items successfully read and assigned; on failure, it returns EOF.
C
#include <stdio.h>
int main()
{
    int a;
    scanf("%d", &a);
    printf("a = %d", a);
    return 0;
}

Input

2

Output

a = 2

Syntax

int scanf(const char *format, ...);

fscanf()

The fscanf() function is a standard library function declared in the <stdio.h> header file. It is used to read formatted input from a file instead of the standard input (stdin).

  • It reads data from the specified file according to the given format specifiers.
  • It accepts a file pointer, a format string, and the addresses of variables where the input values will be stored.
  • On success, it returns the number of input items successfully read and assigned; on failure, it returns EOF.
C
#include <stdio.h>

// Driver Code
int main()
{
    FILE* ptr = fopen("abc.txt", "r");
    if (ptr == NULL) {
        printf("no such file.");
        return 0;
    }
    

    /* Assuming that abc.txt has content in below
       format
       NAME    AGE   CITY
       abc     12    hyderabad
       bef     25    delhi
       cce     65    bangalore */
       
       
    char buf[100];
    while (fscanf(ptr, "%*s %*s %s ", buf) == 1)
        printf("%s\n", buf);

    return 0;
}

Output

CITY
hyderabad
delhi
bangalore

Syntax

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

Difference Between scanf() and fscanf() in C

scanf()fscanf()
Reads formatted input from the standard input (stdin).Reads formatted input from a file.
Input is taken from the keyboard.Input is taken from the specified file using a FILE* pointer.
Syntax: scanf(const char *format, ...);Syntax:fscanf(FILE *stream, const char *format, ...);
Does not require a file pointer.Requires a valid file pointer as the first argument.
Commonly used to accept user input during program execution.Commonly used to read structured data stored in files.
Returns the number of input items successfully read and assigned, or EOF on failure.Returns the number of input items successfully read and assigned, or EOF on failure.
Comment