Reading input safely is an essential part of C programming. While functions like gets() exist, they can be dangerous because they don’t check the buffer size. The safer alternative is fgets(), which allows you to read strings from the user or a file safely.
In this tutorial, you’ll learn how fgets() works, its syntax, examples, and outputs.
What is fgets()?
fgets() is a standard function in <stdio.h> used to read lines of text into a string. It stops reading when:
- A newline character (\n) is encountered.
- The specified number of characters has been read.
- The end-of-file (EOF) is reached.
Because you can specify the buffer size, it prevents buffer overflow—something gets() cannot do.
Syntax
// Syntax of fgets() in C
char *fgets(char *str, int n, FILE *stream);
Parameters:
- str: Array to store the input.
- n: Maximum number of characters to read (including \0).
- stream: Input source (stdin for keyboard or a file pointer).
Return Value:
- Returns str if successful.
- Returns NULL if an error occurs or EOF is reached.
Example 1: Reading Input from the User
// Example: Reading input using fgets()
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
printf("Hello, %s", name);
return 0;
}
Sample Output 1:
Enter your name:
NetizensHello, Netizens
Explanation:
- fgets() reads up to 49 characters and adds a null terminator.
- If the input is shorter than the buffer, it stops at the newline.
Example 2: Removing the Newline Character
fgets() keeps the newline (\n) if the user presses Enter. To remove it:
// Example: fgets() with newline removal
#include <stdio.h>
#include <string.h>
int main() {
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
// Remove newline character if present
name[strcspn(name, "\n")] = '\0';
printf("Hello, %s", name);
return 0;
}
Sample Output 2:
Enter your name:
NetizensHello, Netizens
Explanation:
- strcspn(name, “\n”) finds the newline position and replaces it with \0.
- The string is now clean for printing or comparisons.
Example 3: Reading a Limited Number of Characters
// Example: fgets() with limited buffer size
#include <stdio.h>
int main() {
char buffer[10];
printf("Enter a string: ");
fgets(buffer, sizeof(buffer), stdin);
printf("You entered: %s", buffer);
return 0;
}
Sample Output 3:
Enter a string: Hello World
You entered: Hello Wor
Explanation:
- The buffer size is 10, so fgets() reads 9 characters and adds the null terminator.
- The newline character is included if space allows.
Example 4: Reading from a File
// Example: fgets() reading from a file
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
char line[50];
if(file) {
while(fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);
} else {
printf("Could not open the file.\n");
}
return 0;
}
Assume example.txt contains:
Hello World
C programming is fun
fgets() is safe
Sample Output 4:
Hello World
C programming is fun
fgets() is safe
Explanation:
- Reads one line at a time, up to the buffer size.
- Safe and avoids buffer overflow when reading files.
gets() vs fgets()
Feature |
gets() |
fgets() |
Buffer Control |
No control → unsafe |
Can set buffer size → safe |
Newline Handling |
Removes newline |
Keeps newline |
Input Source |
Keyboard only |
Keyboard or file |
Error Handling |
Cannot detect errors |
Returns NULL on error or EOF |
Status |
Deprecated in modern C |
Recommended and widely used |
Tips for Using fgets()
- Use a large enough buffer for input.
- Remove the newline if needed.
- Don’t mix fgets() with scanf() carelessly; leftover input can cause issues.
- Use it for file reading to safely read line by line.
Also Read: How to get the length of a string in python
Summary
fgets() is a safe, reliable, and flexible way to read strings in C. It works for both keyboard input and file reading, preventing common mistakes like buffer overflow.
By practicing with fgets(), you’ll be able to handle user input safely and write more robust C programs.
FAQs
1. What is the difference between gets() and fgets() in C?
gets() is unsafe as it doesn’t check the buffer size, which may cause a buffer overflow. fgets() is safe because you can set the buffer size.
2. Does fgets() include the newline character?
Yes. If there’s enough space in the buffer, fgets() keeps the newline (\n). You can remove it manually using strcspn() or other methods.
3. Can fgets() read input from a file?
Yes. fgets() can read strings both from stdin (keyboard input) and from a file pointer. It’s commonly used to read file data line by line.
4. What happens if I enter more characters than the buffer size in fgets()?
fgets() only reads up to n-1 characters and adds a null terminator. Extra characters remain in the input buffer until read again.