fgets

From Wikipedia, the free encyclopedia

fgets is a function in C programming language that reads a string of characters with a specific length from a given file stream source. As far as traceable, fgets stands for file get string. It is included in the C standard library header file stdio.h.

The fgets function terminates reading after a new-line character is found. 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. The prototype of the function is as follows:

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

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

Contents

[edit] Sample usage

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, MAX_LEN, stdin) != NULL)
        puts(str_buf);
 
  return 0;
}

[edit] Use in POSIX utilities

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

[edit] Limitations

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

The Gnu function readlinebuffer() can be a useful alternative to fgets() in such applications. For example, the Gnu implementation of comm (Unix) uses this technique.

Advanced applications can avoid buffer limitations by using mmap.

[edit] See also

Languages