| Types and objects | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Defined in header <stdio.h> | ||
char* fgets(char* str,int count,FILE* stream); | (until C99) | |
char* fgets(char*restrict str,int count,FILE*restrict stream); | (since C99) | |
Reads at mostcount-1 characters from the given file stream and stores them in the character array pointed to bystr. Parsing stops if a newline character is found (in which casestr will contain that newline character) or if end-of-file occurs. If bytes are read and no errors occur, writes a null character at the position immediately after the last character written tostr.
Contents |
| str | - | pointer to an element of a char array |
| count | - | maximum number of characters to write (typically the length ofstr) |
| stream | - | file stream to read the data from |
str on success, null pointer on failure.
If the end-of-file condition is encountered, sets theeof indicator onstream (seefeof()). This is only a failure if it causes no bytes to be read, in which case a null pointer is returned and the contents of the array pointed to bystr are not altered (i.e. the first byte is not overwritten with a null character).
If the failure has been caused by some other error, sets theerror indicator (seeferror()) onstream. The contents of the array pointed to bystr are indeterminate (it may not even be null-terminated).
POSIX additionally requires thatfgets setserrno if a read error occurs.
Although the standard specification isunclear in the cases wherecount<=1, common implementations do
#include <stdio.h>#include <stdlib.h> int main(void){FILE* tmpf=tmpfile();fputs("Alan Turing\n", tmpf);fputs("John von Neumann\n", tmpf);fputs("Alonzo Church\n", tmpf); rewind(tmpf); char buf[8];while(fgets(buf,sizeof buf, tmpf)!=NULL)printf("\"%s\"\n", buf); if(feof(tmpf))puts("End of file reached");}
Output:
"Alan Tu""ring""John vo""n Neuma""nn""Alonzo ""Church"End of file reached
(C11)(C11)(C11) | reads formatted input fromstdin, a file stream or a buffer (function)[edit] |
(removed in C11)(C11) | reads a character string fromstdin (function)[edit] |
| writes a character string to a file stream (function)[edit] | |
(dynamic memory TR) | read from a stream into an automatically resized buffer until delimiter/end of line (function)[edit] |
C++ documentation forfgets | |