fgets is a function in the C programming language that reads a limited number of characters from a given file stream source into an array of characters.[1] fgets stands for file get string. It is included in the C standard library header file stdio.h. The prototype of the function is as follows:

char* fgets(char *string, int length, FILE * stream);

The function terminates reading either after a new-line character is found or end-of-file is reached, or after (length - 1) characters have been read. If a new-line was reached it is included in the string as the last character before the null character. The length argument includes space needed for the null character which will be appended to the end of the string. As a result, to read N characters, the length specification must be specified as N+1. The string read is returned if at least one character was read and no error occurred, otherwise a NULL-pointer is returned.

The stream argument specifies the stream from which the string be read. stdin is commonly used here, for reading from the standard input. Otherwise, a FILE * value returned by the fopen() function is used.

Sample usage edit

The following code reads characters from the console input and prints them out 20 in a line with the puts function until an EOF occurs.

#include <stdio.h>

#define MAX_LEN 20

int main(void)
{
  char str_buf[MAX_LEN + 1]; // One extra byte needed
                             // for the null character

  while(fgets(str_buf, sizeof str_buf, stdin) != NULL)
	puts(str_buf);

  return 0;
}

Use in POSIX utilities edit

For compliance with POSIX utility line lengths, the definition LINE_MAX (generally found in limits.h) is often used to size the character buffer.

Limitations edit

The fixed buffer size imposed by fgets() is cumbersome in applications which need to handle arbitrarily long lines of text.

POSIX.1-2008-conforming systems provide a function called getline() (originally a GNU extension[2]), which will read an entire line, reallocating the buffer if it is not long enough.[3]

Advanced applications can avoid buffer limitations by using mmap.

References edit

  1. ISO/IEC 9899:1999 specification (PDF). p. 296, § 7.19.7.2.
  2. http://www.gnu.org/software/libc/manual/html_node/Line-Input.html#index-getline-993
  3. http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html

External links edit