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.

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

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

ismail 34 ankara
ali 5 canakkale
elif 9 istanbul

We will name fscanf_example.c

#include <stdio.h> 
int main() 
FILE* ptr = fopen("test.txt","r"); 

char* buf[100]; 
while (fscanf(ptr,"%*s %*s %*s ",buf)==1) 
printf("%s\n", buf); 

return 0; 
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.

$ gcc -o fscanf_example fscanf_example.c

And binary file fscanf_example can be run like below.

$ ./fscanf_example

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.

while (fscanf(ptr,"%*s %*s %*s ",buf)==1) 
printf("%s\n", buf);

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

1 thought on “How To Read Input with fscanf() function In C Programming Language?”

  1. 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 Comment