Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
fgets() and gets() in C
In C, fgets() and gets() are functions used to read strings from input streams. The key difference is that fgets() is safe and checks array bounds, while gets() is unsafe and has been removed from C11 standard due to buffer overflow vulnerabilities.
fgets() Function
The fgets() function reads a string from a specified stream until a newline character or the specified limit is reached −
Syntax
char *fgets(char *string, int size, FILE *stream);
Parameters:
- string − Pointer to character array where the string will be stored
- size − Maximum number of characters to read (including null terminator)
-
stream − Input stream (commonly
stdinfor standard input)
Example
#include <stdio.h>
#define MAX_SIZE 50
int main() {
char buffer[MAX_SIZE];
printf("Enter a string: ");
fgets(buffer, MAX_SIZE, stdin);
printf("You entered: %s", buffer);
return 0;
}
Enter a string: Hello TutorialsPoint You entered: Hello TutorialsPoint
gets() Function (Deprecated)
The gets() function reads a string from standard input but does not check array bounds, making it vulnerable to buffer overflow attacks. It has been removed from C11 standard.
Syntax
char *gets(char *string); // DEPRECATED - DO NOT USE
Safe Alternative to gets()
Instead of using gets(), use fgets() with stdin −
#include <stdio.h>
#include <string.h>
int main() {
char text[100];
int i;
printf("Enter a string: ");
fgets(text, sizeof(text), stdin);
// Remove newline character if present
text[strcspn(text, "<br>")] = '\0';
// Convert to uppercase
for (i = 0; text[i] != '\0'; i++) {
if (text[i] >= 'a' && text[i] <= 'z') {
text[i] = text[i] - 32;
}
}
printf("String in Upper Case: %s<br>", text);
return 0;
}
Enter a string: hello world String in Upper Case: HELLO WORLD
Comparison
| Feature | fgets() | gets() |
|---|---|---|
| Buffer Overflow Protection | Yes | No |
| Newline Character | Included in string | Not included |
| Standard Status | Available | Removed in C11 |
| Safety | Safe | Unsafe |
Key Points
- Always use
fgets()instead ofgets()for safe string input -
fgets()includes the newline character in the string; usestrcspn()to remove it - The size parameter in
fgets()should be the actual size of the buffer
Conclusion
fgets() is the recommended function for reading strings in C due to its buffer overflow protection. Never use gets() as it poses serious security risks and has been deprecated.
