fgets - C stdio.h

C examples for stdio.h:fgets

Type

function

From


<cstdio>
<stdio.h>

Prototype

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

Description

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.

Parameters

ParameterDescription
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.

Return Value

On success, the function returns str.

If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned.

Example

This following code reads the first line or the first 99 characters, whichever comes first, and prints them on the screen.

Demo Code


#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;
}

Related Tutorials