Fgets
From Wikipedia, the free encyclopedia
- The correct title of this article is fgets. The initial letter is shown capitalized due to technical restrictions.
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.
[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 string[MAX_LEN + 1]; /* One extra byte needed * for the null character */ while(fgets(string, MAX_LEN + 1, stdin) != NULL) puts(string); return 0; }