How To Read Input with fscanf() function In C Programming Language? – POFTUT

How To Read Input with fscanf() function In C Programming Language?

C programming language libraries provide some standard functions which can be used in different platforms like Linux and Windows. In this tutorial, we will learn how to use fscan()function, return values and parameters with examples.

Declaration and Parameters

fscanf() function will accept a file stream in FILE type and format specifiers as char type. In this case, format specifiers are important because the given file will be read in this format like "%s %s %s" which means 3 strings with separated with spaces.

Return Value

fscanf functions will return data with pointers provided as parameter. But as a function, it will also return the function operational status as int . If operations are successfully completed it will return 1 as an integer.

Read Example

We will start with a simple example where we will read data from the file named test.txt with fscanf() function in the %s %s %s format.

Our data file will be named test.txt

We will name fscanf_example.c

Read File with fscanf() Function

Read File with fscanf() Function

We will name the source code as fscanf_example.c and compile with the following gcc command.

LEARN MORE  scanf() Function In C and C++ To Read Input From Command Line

And binary file fscanf_example can be run like below.

echo '

Read To The EOF (End Of File)

As examined in the previous example we can read to the end of the file with fscanf() function . We will use the return value of fscanf() . If the return value is equal to 1 which means a data can be read and the file has not reached the end.

1 Response

  1. dathuynh says:

    Hi Ismail, I read your example and found a issue with the code. In the fscanf function, you used a “*” for 3 variables, it means you skip all the value. But the running example you extract the AGE field, so I think you should change the 2th “%s” instead “%*s”.

Leave a Reply

Your email address will not be published. Required fields are marked *