Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C library function - fgets()

C library function - fgets()

C Standard Library - <stdio.h> C Standard Library -

Description

C library function **char *fgets(char str, int n, FILE stream) Reads a line from the specified stream and stores it in the string pointed to by str When (n-1) characters are read, or when a newline character is read, or when the end of the file is reached, it stops, depending on the case.

Declaration

The following is the declaration of the fgets() function.



char *fgets(char *str, int n, FILE *stream)

Parameters

Return Value

If successful, the function returns the same str argument. If the end of the file is reached or no characters are read, the content of str remains unchanged and a null pointer is returned.

If an error occurs, a null pointer is returned.

Example

The following example demonstrates the use of the fgets() function.

Example

#include

int

main

(

)

{

   FILE

fp

;

   

char

str

[

60

]

;

   

/* Open the file for reading */

   fp

=

fopen

(

"file.txt"

,

"r"

)

;

   

if

(

fp

==

NULL

)

{

     

perror

(

"Error opening file"

)

;

     

return

(

1

)

;

   

}

   

if

(

fgets

(

str

,

60

,

fp

)

!=

NULL

)

{

     

/* Write content to standard output stdout */

     

puts

(

str

)

;

   

}

   

fclose

(

fp

)

;

   

   

return

(

0

)

;

}

Suppose we have a text file file.txt, whose content is as follows. The file will be used as input in the example:



We are in 2014

Let's compile and run the above program, which will produce the following result:



We are in 2014

C Standard Library - <stdio.h> C Standard Library -