C fgets
Created By: chatGPT
C provides several functions for input and output, with one of the most common being
fgets
. This function reads a string from a specified file stream (like stdin for standard input) and is very useful for handling user input safely, avoiding buffer overflows.char buffer[100];
if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
// Process input
}
The
fgets
function takes three arguments: the first is a pointer to the character array where text will be stored, the second is the maximum number of characters to read (including the null terminator), and the third is the file pointer from which to read (e.g., stdin
). It stops reading when either a newline character is encountered, the end of the file is reached, or it has read the specified number of characters.char text[50];
fgets(text, sizeof(text), stdin);
It’s important to note that
fgets
retains the newline character in the string. If you want to remove this newline character, you can do so manually by checking and replacing it with a null terminator.text[strcspn(text, "\n")] = 0; // Removes newline character
Using
fgets
can improve the safety of your program when compared to older functions like gets
, which does not check for buffer overflows. Thus, always prefer fgets
when reading strings.#include <stdio.h>
#include <string.h>
int main() {
char input[100];
printf("Enter input: ");
fgets(input, sizeof(input), stdin);
// Clean up newline character
input[strcspn(input, "\n")] = 0;
printf("You entered: %s\n", input);
return 0;
}