fgets em c

fgets() is a C library function that is used to read a line from a file or from the standard input stream (stdin). It has the following syntax:

char fgets(char str, int n, FILE *stream);
  • str is the pointer to the character array where the line is stored.
  • n is the maximum number of characters to be read (including the newline character).
  • stream is the pointer to a FILE object that identifies the input stream.

The fgets() function reads characters from the input stream until either n-1 characters have been read, a newline character is encountered, or the end-of-file (EOF) is reached. The newline character, if encountered, is also stored in the string.

After reading the line, fgets() returns the pointer to the string str if successful, or NULL if there is an error or if the end-of-file is reached before any characters are read.

Here is an example usage of fgets():

#include <stdio.h>

int main() {
    char str[100];

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    printf("You entered: %s", str);

    return 0;
}

In this example, the program prompts the user to enter a string, and fgets() is used to read the input from the standard input stream (stdin) into the str array. The entered string is then printed back to the console.

Note: It's important to check the return value of fgets() to handle any errors that may occur during reading.