How to Use fgets() in C: Safe String Input Handling with Practical Examples

1. Introduction

The fgets function is a standard library function in C used for safely reading strings. It is widely used as a safer alternative to the traditional gets function. In this article, we’ll explain how to use fgets, discuss its advantages and disadvantages, and provide practical tips for secure input handling.

2. Basic Usage of fgets

2.1 Syntax and Parameters of fgets

The basic syntax of fgets is as follows:

char *fgets(char *str, int n, FILE *stream);
  • str: The buffer where the input string will be stored
  • n: The maximum number of characters to read (buffer size)
  • stream: The input stream (typically stdin)

2.2 Sample Code Example

Here is a basic example of using fgets:

char buffer[50];
fgets(buffer, 50, stdin);
printf("Entered string: %s", buffer);

This code reads up to 49 characters from the user (50 including the null terminator) and prints the result.

侍エンジニア塾

3. Advantages and Drawbacks of fgets

3.1 Safety Compared to gets

The gets function can cause buffer overflows and poses serious security risks. In contrast, fgets allows you to specify the maximum number of characters to read, preventing buffer overflow.

3.2 Handling Newline Characters and Buffer Issues

Because fgets includes the newline character when reading input, your strings may contain unexpected newlines. Additionally, if the input exceeds the buffer size, the remaining data will stay in the input stream.

4. Methods for Safe Input Handling

4.1 Removing the Newline Character

Strings read with fgets may include a newline character. To remove it, add the following code:

char *newline = strchr(buffer, '\n');
if (newline) {
    *newline = '\0';
}

This code replaces the newline character with a null terminator, cleaning up the string.

4.2 Clearing the Buffer

If the user input exceeds the buffer size, extra characters may remain in the input stream. To clear the remaining data, add the following process:

while ((getchar()) != '\n' && !feof(stdin));

This loop clears the input stream until it reaches a newline or the end of file.

5. Important Notes When Using fgets

5.1 Error and Exception Handling

fgets returns a pointer if successful and NULL on failure. Proper error handling is crucial when working with fgets.

if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
    // Error handling
}

5.2 Best Practices

When using fgets, always consider the buffer size and error handling. Validate your input and watch out for buffer overflows to keep your code safe.

6. Practical Code Example Using fgets

6.1 Input Validation and Sanitization

Input validation and sanitization are essential when processing user input. The following code example accepts only numeric input:

char input[10];
if (fgets(input, sizeof(input), stdin) != NULL) {
    // Remove newline character
    char *newline = strchr(input, '\n');
    if (newline) {
        *newline = '\0';
    }

    // Accept only numbers
    if (strspn(input, "0123456789") == strlen(input)) {
        printf("Entered number: %s\n", input);
    } else {
        printf("Invalid input. Please enter numbers only.\n");
    }
}

7. Conclusion

The fgets function is a convenient tool for safely reading strings in C. Compared to gets, it significantly reduces the risk of buffer overflow. However, handling newline characters and clearing the buffer properly is necessary when using fgets. Use the techniques introduced in this article to implement secure and efficient input processing in your programs.