C Function Fgets
## C Library Function - `fgets()`
The `fgets()` function in C is a standard library function defined in the `` header. It is designed to read a line of text or a limited number of characters from a specified input stream and store them into a string buffer.
Unlike the deprecated and unsafe `gets()` function, `fgets()` prevents buffer overflows by allowing you to specify the maximum number of characters to read.
---
## Description
The `fgets()` function reads characters from the specified `stream` and stores them as a C-string into `str`. The function stops reading when one of the following conditions is met:
1. **`n - 1` characters** have been read.
2. A **newline character (`\n`)** is encountered (the newline character is retained in the buffer).
3. The **End-of-File (EOF)** is reached.
After reading, `fgets()` automatically appends a terminating null character (`\0`) to the end of the string.
---
## Syntax & Declaration
```c
char *fgets(char *str, int n, FILE *stream);
```
### Parameters
* **`str`**: A pointer to an array of chars (buffer) where the retrieved string will be stored.
* **`n`**: The maximum number of characters to read, including the terminating null character (`\0`). Typically, you pass the size of the destination buffer `str`.
* **`stream`**: A pointer to a `FILE` object that identifies the input stream. To read from the standard keyboard input, use `stdin`.
### Return Value
* **On Success**: The function returns the same pointer passed as the `str` argument.
* **On EOF / No Characters Read**: If the end-of-file is reached and no characters have been read, the contents of `str` remain unchanged, and a `NULL` pointer is returned.
* **On Error**: If a read error occurs, a `NULL` pointer is returned.
---
## Code Examples
### Example 1: Reading from a File
The following example demonstrates how to use `fgets()` to read a line of text from an external file.
```c
#include
int main()
{
FILE *fp;
char str;
/* Open the file for reading */
fp = fopen("file.txt", "r");
if (fp == NULL) {
perror("Error opening file");
return -1;
}
/* Read a line from the file and print it to stdout */
if (fgets(str, 60, fp) != NULL) {
puts(str);
}
fclose(fp);
return 0;
}
```
#### Input (`file.txt`):
```text
We are in 2024
```
#### Output:
```text
We are in 2024
```
---
### Example 2: Reading Safe Input from `stdin` (Keyboard)
`fgets()` is the recommended standard way to read user input from the console safely.
```c
#include
int main()
{
char name;
printf("Enter your full name: ");
// Read up to 29 characters from standard input
if (fgets(name, sizeof(name), stdin) != NULL) {
printf("Hello, %s", name);
}
return 0;
}
```
---
## Key Considerations & Best Practices
### 1. Handling the Newline Character (`\n`)
If `fgets()` reads a whole line, it includes the newline character (`\n`) in the destination buffer. If you want to print or compare the string without the trailing newline, you should manually strip it:
```c
#include
// Strip trailing newline if present
size_t len = strlen(str);
if (len > 0 && str == '\n') {
str = '\0';
}
```
### 2. `fgets()` vs `gets()`
* **`gets()` (Deprecated/Removed)**: Never use `gets()`. It does not check the bounds of the destination buffer, making your program highly vulnerable to buffer overflow attacks.
* **`fgets()` (Safe)**: Always use `fgets()` because it guarantees that no more than `n - 1` characters will be written to the buffer, preventing memory corruption.
### 3. Handling Leftover Input
If the input line is longer than `n - 1` characters, `fgets()` will read only the first `n - 1` characters. The remaining characters will stay in the input stream buffer and will be read by subsequent input operations. If necessary, you can clear the input buffer using a loop:
```c
int c;
while ((c = getchar()) != '\n' && c != EOF);
```
YouTip