Open In App

scanf() and fscanf() in C

Improve
Improve
Like Article
Like
Save
Share
Report

In C language, scanf() function is used to read formatted input from stdin. It returns the whole number of characters written in it otherwise, returns a negative value.

Syntax:

int scanf(const char *characters_set)

Time Complexity: O(n)

Auxiliary Space: O(n) where n is the length of input.

Many of us know the traditional uses of scanf. Well, here are some of the lesser-known facts

How to read only a part of the input that we need? 
For example, consider some input stream that contains only characters followed by an integer or a float. And we need to scan only that integer or float. 

Example:

Input: "this is the value 100", 
Output: value read is 100
Input : "this is the value 21.2", 
Output : value read is 21.2

C




// C program to demonstrate that
// we can ignore some string
// in scanf()
#include <stdio.h>
int main()
{
    int a;
    scanf("This is the value %d", &a);
    printf("Input value read : a = %d", a);
    return 0;
}
// Input  : This is the value 100


Now, assume we don’t know what the preceding characters are but we surely know that the last value is an integer. How can we scan the last value as an integer? 

The below solution works only if the input string has no spaces. For example,

Input

"blablabla 25"

C




// C program to demonstrate use of *s
#include <stdio.h>
int main()
{
    int a;
    scanf("%*s %d", &a);
    printf("Input value read : a=%d", a);
    return 0;
}


Output

Input Value read : 25

Explanation: The %*s in scanf is used to ignore some input as required. In this case, it ignores the input until the next space or newline. Similarly, if you write %*d it will ignore integers until the next space or newline. 

General use of scanf( ):

C




// C program to demonstrate general use of scanf()
#include <stdio.h>
int main()
{
    int a;
    scanf("%d", &a);
    printf("a = %d", a);
    return 0;
}


Input

2

Output

a = 2

The above fact may not seem like a useful trick at the first glance. In order to understand its usage, let us first see fscanf().

fscanf Function in C

Tired of all the clumsy syntax to read from files? well, fscanf comes to the rescue. This function is used to read the formatted input from the given stream in the C language. 

Syntax:

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

fscanf reads from a file pointed by the FILE pointer (ptr), instead of reading from the input stream.

Return Value: It returns zero or EOF, if unsuccessful. Otherwise, it returns the number of arguments successfully printed.

Time Complexity: O(n)

Auxiliary Space: O(n) where n is the length of the input.

Example 1: Consider the following text file abc.txt 

NAME    AGE   CITY
abc 12 hyderabad
bef 25 delhi
cce 65 bangalore

Now, we want to read only the city field of the above text file, ignoring all the other fields. A combination of fscanf and the trick mentioned above does this with ease 

C




// C Program to demonstrate fscanf
#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

Example 2: Consider the following binary file program.bin

n1    n2    n3
1 5 6
2 10 11
3 15 16
4 20 21

To read all values of n1, n2 & n3 of the bin, we are using fscanf()

C




#include <stdio.h>
#include <stdlib.h>
 
struct threeNum{
    int n1, n2, n3;
};
 
int main(){
    int n;
    struct threeNum num;
    FILE *fptr;
    if ((fptr = fopen("program.bin","rb")) == NULL){
        printf("Error! opening file");
         // Program exits if the file pointer returns NULL.
         exit(1);
         }
     for(n = 1; n < 5; ++n){
         fread(&num, sizeof(struct threeNum), 1, fptr);
         printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
     }
     fclose(fptr);
     return 0;
}
 
//Code submitted by Susobhan Akhuli


Output

n1: 1   n2: 5   n3: 6
n1: 2 n2: 10 n3: 11
n1: 3 n2: 15 n3: 16
n1: 4 n2: 20 n3: 21

Let us see the differences in a tabular form -:

  scanf() fscanf()
1. It is used to read standard input. This function is used to read input from a file
2.

Its syntax is -:

scanf(const char *format, …)

Its syntax is -:

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

3. It requires Format specifiers to take input of a particular type. It reads the stream in the form of byte
4.

It takes three parameters that are -:

Whitespace character , Non-whitespace character,Format specifiers

It is defined in header file #include <stdio.h>

 



Last Updated : 16 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads