C examples for stdio.h:fgets
function
<cstdio> <stdio.h>
char * fgets ( char * str, int num, FILE * stream );
Reads characters from stream and stores them as a string until num-1 characters have been read or either a newline or the end-of-file is reached.
Parameter | Description |
---|---|
str | Pointer to an array of chars. |
num | Maximum number of characters to be copied into str. |
stream | Pointer to a FILE object that identifies an input stream. stdin can be used as argument to read from the standard input. |
On success, the function returns str.
If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned.
This following code reads the first line or the first 99 characters, whichever comes first, and prints them on the screen.
#include <stdio.h> int main()/* w w w. j av a 2 s. c om*/ { FILE * pFile; char mystring [100]; pFile = fopen ("main.cpp" , "r"); if (pFile == NULL) { perror ("Error opening file"); return -1; } if ( fgets (mystring , 100 , pFile) != NULL ) puts (mystring); fclose (pFile); return 0; }