fgets() – I/O Function

fgets() – I/O Function

How is “fgets()” used in C++?
How to read string from stream?

Explanation

fgets() is an I/O function that reads upto a character less from the specified number in “num” attribute, then places them into the character array pointed by the stream. On success the function returns the same “str” parameter, or if the EOF is encountered with no characters been read a null pointer is returned the end of C string.

Syntax:

char *fgets( char *str, int num, FILE * stream);

Example :

#include
int main()
{
FILE *str=fopen(“fgetseg.txt”, “r”);
char n[150];
fgets (n, 100 , str);
printf(“First line of text file is: %sn”, n);
fclose (str);
return 0;
}

Result :

First line of text file is: HIIIIIIIIIIIIIIIII

In the above example the “fgets()” is used to read the first line of the text file that is stored in the
character array “n”.





Leave a Reply

Your email address will not be published. Required fields are marked *