scanf() and fscanf() in C
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.
int scanf(const char *characters_set)
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.
Input: "this is the value 100", Output: value read is 100 Input : "this is the value 21.2", Output : value read is 21.2
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 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.
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.
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, if unsuccessful. Otherwise, it returns The input string, if successful.
Example: Consider the following text file abc.txt
NAME AGE CITY abc 12 hyderbad 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
CITY hyderbad delhi bangalore
This article is contributed by Nikhil Chakravartula. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.