C fgets() Function Tutorial

In this section, we will learn what the fgets() function is and how to use it in C.

fgets() Function in C

The `fgets` function is used to read a line from an incoming input stream and store it into a string-array.

fgets() Function Syntax

Here’s the prototype of this function:

char *fgets(char *str, int n, FILE *stream)

fgets() Function Parameters

The `fgets` function accepts 3 arguments:

  1. The first argument is the address of the array in which the incoming stream should be stored in.
  2. The second argument is the maximum number of characters that are allowed to be stored in the destination array. If this argument has the value `n`, fgets() reads up to `n-1` characters or until the newline character, whichever comes first.

Note:

  • The `n-1` is because the last element is automatically set to the null `\0` character.
  • We use this argument in order to stop the function from unintentionally overflowing the destination array.
  • This function also stores the newline character if it appeared in the input stream.
  1. The third argument indicates which file to read. To read from the keyboard, use `stdin` (for standard input) as the argument; this identifier is defined in `stdio.h` header file.

fgets() Function Return Value

This function returns the address of the destination array that we set for its first argument on a successful operation and a null pointer in case no data has been read.

Example: Input a String in C

#include <stdio.h>
int main() {

    char array[30];

    puts("Please enter something: ");
    fgets(array, 30, stdin);

    printf("This is what you've entered: \n %s",array);

    return 0;
}

Output:

Please enter something:

My name is John Doe and I'm a professional C programmer!

This is what you've entered:

My name is John Doe and I'm a

In this example, we tried to enter more than 30 characters but because in the `fgets` function we set the second argument to 30, this function will stop reading more than 29 characters in order to stop the destination array from being overflowed.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies