fgets() Function in C
Overview
We all know about the scanf() function, it is the most commonly used function to take input from the console in C language, and it works great with inputs being an int, a float, a char etc, but when it comes to taking string input with whitespaces, then using scanf() does not goes very well.
For Example:
Input: Hello World
Output:
We can see that, scanf() only captured the input till it encountered the first whitespace in the string, and hence stores the value till that only, and because of this it becomes hectic to take multiword or multiline string inputs using scanf().
We can easily avoid the above issue, by using the fgets() function
What is fgets() Function in C
fgets() is a pre-defined function in C present in the stdlib.h header file, it is used to read a string or a text line up to n characters from a specified file or the console, and then it stores that value into the specified string variable. It keeps reading the character inputs till either of the below condition satisfied:
- (n-1) characters have been read from the stream.
- a new line character is encountered
- end of file is reached
Although, the function fgets() stops taking the input once a newline character is found but it surprisingly appends that at the end of our string variable.
Syntax of fgets() Function in C
Parameters of fgets() Function in C
In the above syntax, we have
- char *str: a pointer to an array of characters where the read values will be stored
- int n: maximum number of characters to be read
- FILE *stream: pointer to the file stream from where the input is to be taken (it can be replaced with stdin when taking input from the standard input ie through the console)
Return Value of fgets() Function in C
- If the reading operation is completed successfully, then the fgets() function will return the pointer str itself where it stores the input.
- If the operation has been unsuccessful, then the fgets() function will return a null pointer, there can be several reasons for this to happen. For example - If the end of the file is reached before reading any character or if some other error occurred during the reading process, then the function fgets() will return a null pointer.
- If the passed value of n ie. the maximum number of characters to read, is less than or equal to 0, then it will indicate a domain error.
- And if the value of n is passed as 1, then it will be a valid thing, but remember it will only store the null terminator, as there is enough space for1 character only, and that will be the null terminator, which means, there will be no data read from the stream specified.
Example of fgets() Function in C
Reading From the Console using gets() Function in C
Input: Hello World
Output:
A Quick Explanation:
- We are declaring a char array with size 20 and are asking the user to enter a string.
- Then we are taking the user input using the function fgets(), here the str means this is the place where the input string will be stored, 20 means a maximum of 20 chars should be read, stdin means input source is the console i.e in simple words input should be taken from user's keyboard.
Reading From a File using gets() Function in C
Input: The file contains
Output:
A Quick Explanation:
- We are declaring a char array with size 20.
- After that, we are declaring a file pointer to keep track of the file we are accessing and then open the specified file in read mode, to read its data.
- Generally, the function fopen() returns the file pointer, but in case some error has occurred and the file opening was unsuccessful, then fopen() will return a null pointer, so there we are checking, if the file opening was unsuccessful, if yes then printing the error message.
- And if the file opening was successful, then we are using the function fgets() to read the file data and store that into the specified char array, here str means the char array where the read data will be stored, 20 means a maximum of 20 characters should be read, filePtr means this is the source from where we have to read the data.
- In the end, we are calling the fclose() function to close the file we opened, it is optional, but it is a recommended practice.
As we know, the function fgets() stops taking the input when a new line is encountered, this is why it only read "Hello World" and skipped the second line "Hello World again".
Some More Examples of fgets() Function in C
Reading Multiple Lines Through fgets() Function in C Using stdin
Input is given through stdin as
Output:
A Quick Explanation:
- Unlike above, where we read only one line through stdin, here we will be reading multiple lines using a loop.
- Firstly we are initializing a char array of size 100 with an empty string, then after we are making a temporary array to store the user input for each iteration of the loop.
- Then we are taking the user input and store that in the temp array, then after we are checking on the condition that if the user enters the character q, if yes, then we are exiting the loop.
- If no, then we are concatenating the temp array into the main str array.
- Finally print the string str.
Reading the Complete File Through fgets() Function in C Using a Loop
Input: The file contains
Output:
A Quick Explanation:
- We are declaring a char array with size 100.
- After that, we are declaring a file pointer to keep track of the file we are accessing and then open the specified file in read mode, to read its data.
- Generally, the function fopen() returns the file pointer, but in case some error has occurred and the file opening was unsuccessful, then fopen() will return a null pointer, so there we are checking, if the file opening was unsuccessful, if yes then printing the error message.
- And if the file opening was successful, then we are entering into a loop and using the function gets() we are reading the file data line by line and storing that into the specified char array, here str means the char array where the read data will be stored, 20 means a maximum of 20 characters should be read, filePtr means this is the source from where we have to read the data.
- The loop will exit once the end of the file is reached.
- In the end, we are calling the fclose() function to close the file we opened, it is optional, but it is a recommended practice.
Conclusion
- fgets() function can be used to read a string or a text line input up to n characters from stdin as well as from a file.
- Syntax : fgets(char *str, int n, FILE *stream), where
- char *str is a pointer to an array where the read values will be stored
- int n is the maximum number of characters that can be read
- FILE *stream is where the inputs are to be taken, it can be replaced with stdin if we want to take input from the console.
- The function fgets() reads the input, till either
- (n-1) characters have been read from the stream (n is the number of characters to copy)
- a new line is encountered
- end of file is reached
- The function fgets() returns the pointer str itself if the reading operation was successful else if it was unsuccessful, then it will return the null pointer.