C fscanf() Function Tutorial

In this section, we will learn what the fscanf() function is and how it works in C.

Reading from a File in C: C fscanf() Function

The `fscanf()` function is just like the `scanf()` function with the exception that it can get its content not just from the input stream but also from an opened file other than the input stream. Basically, it will take the address of an opened file as its first argument, and that file will be the source of the incoming stream.

Note: the prototype of this function exists in the `stdio.h` header file and so we need to include the file in order to work with this function.

C fscanf() Function Syntax:

Here’s the prototype of the function:

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

C fscanf() Function Parameters

The first argument of the function is the address of the memory-space allocated to the FILE-structure of the target file.

Note: we get this address via the call to the `fopen()` function.

The rest of the arguments for the `fscanf` function are exactly like the `scanf()` function. (Read the scanf() section to learn more about other arguments like the format specifier, etc.)

C fscanf() Function Return Value

The method returns the number of input items that were read from the target file.

Example: using fscanf() function in C

#include <stdio.h>
#include <stdlib.h>

int main() {

    //Call the the fopen function in order to open the file in read mode.
    FILE *file = fopen("G:/fileOne.txt","r");
    //if there was a problem on opening the file, exit the program.
    if (file == NULL){
        printf("Could not open the file");
        exit(EXIT_FAILURE);

    }

    char string[100];
    fscanf(file, "%s",string);
    fprintf(stdout, "%s",string);

    fclose(file);


    printf("\nDone\n");
    return 0;
}

Output:

Hello,

Done
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies