Standard Library Functions in C

adplus-dvertising
fgets() Function
Previous Home Next

Description

The C library function, the fgets() function reads characters from the stream pointed to by stream. The fgets() function shall read bytes from stream into the array pointed to by str, until n-1 bytes are read, or a is read and transferred to str, or an end-of-file condition is encountered. The string is then terminated with a null byte.

Declaration

Following is the declaration for fgets() function.

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

Parameters

str - This is a pointer to the string or array of characters where you want to save the string after you read it.

n - This is the total number of characters you want to read. Remember to include the ending null character.

stream - This is the pointer to the File object from where you want to read the string.

Return Value

The fgets function returns str. The fgets function will return a null pointer if an error occurs while trying to read the stream or the end of the stream is encountered before any characters are stored.

Example

#include <stdio.h>

int main()
{
  char name[10];
  printf("Who are you? ");
  fgets(name,10,stdin);
  printf("Glad to meet you, %s.\n",name);
  return(0);
}

Output

Who are you?
You enter a name on your keyboard. Example: Sanju Samuel
Glad to meet you, Sanju Sam.
Previous Home Next