fgets langage c
Explanation of fgets in C
The fgets
function in C is used to read a line of text from a file or from the standard input (keyboard) and store it in a character array. It is commonly used for reading user input from the command line.
Here is an example of how fgets
is used:
char line[512];
if (fgets(line, 512, stdin) == NULL) {
printf("Error reading input.\n");
exit(1);
}
In this example:
- char line[512];
declares a character array called line
with a size of 512 characters to store the input.
- fgets(line, 512, stdin)
reads a line of text from the standard input (keyboard) and stores it in the line
array. The 512
specifies the maximum number of characters to read, including the newline character.
- The if
statement checks if fgets
returns NULL
, which indicates an error occurred while reading the input. If an error occurs, an error message is printed and the program exits.
fgets
is preferred over scanf
for reading input because it is safer and more robust. Unlike scanf
, fgets
reads a whole line of text, including spaces, and stores it in a character array. This helps avoid buffer overflow vulnerabilities that can occur when using scanf
to read input.