fgets() in C
In C, fgets() is a built-in function defined in <stdio.h> header file. It reads the given number of characters of a line from the input stream and stores it into the specified string. This function stops reading the characters when it encounters a newline character, has read the given number of characters, or reaches the end-of-file (EOF).
Example:
#include <stdio.h>
int main() {
char buff[100];
int n = 10;
printf("Enter a string: \n");
// Read input from the user
fgets(buff, n, stdin);
printf("You entered: %s", buff);
return 0;
}
Output
Enter a string: This is Geeks {entered by user} You entered: This is Geeks
Explanation : In this program, fgets() reads will read up to 9 characters or until a newline (\n) is encountered from the standard input (stdin) and stores them in the array buff, ensuring it is null-terminated.
Syntax
fgets(buff, n, stream);
Parameters:
- buff: Pointer to the string buffer where the input will be stored.
- n: The maximum number of characters to read (including the null terminator).
- stream: The input stream, typically stdin for reading from the keyboard.
Return Value:
- Returns the pointer to buff if successful.
- Returns NULL if an error occurs or the end-of-file (EOF) is reached.
Examples of fgets()
The following examples demonstrate how to use the fgets() function in C programs:
Reading from a File
#include <stdio.h>
int main() {
FILE *fptr = fopen("in.txt", "r");
// Reading the file data using fgets() in the
// form of a block of size 30 bytes
char buff[30];
fgets(buff, sizeof(buff), fptr);
printf("%s", buff);
fclose(fptr);
return 0;
}
Assume that in.txt contains the following data:
The quick brown fox jumps
over the lazy dog.
This sentence contains all letters
of English Alphabets.
Output:
The quick brown fox jumps
Reading from Keyboard ( User Input )
#include <stdio.h>
#include <string.h>
int main() {
char name[20];
printf("Enter your name: \n");
fgets(name, sizeof(name), stdin);
printf("Hello, %s", name);
return 0;
}
Output
Enter your name: Abhishek //Entered by user Hello, Abhishek
gets() vs fgets()
Following table lists the primary differences between the gets() and fgets() functions:
Aspect | gets() | fgets() |
---|---|---|
Buffer Size Control | No size control so may lead to buffer overflow. | Allows size control preventing buffer overflow. |
Newline Handling | Discards newline character. | Retains newline character. |
Input Source | Can read from stdin only. | Can read from any input stream including stdin. |
Error Handling | Cannot detect errors or EOF so no way to handle read failures. | Returns NULL on error or EOF so can handle read failure efficiently. |
Status | Deprecated in C11 and later. | Recommended and widely used. |