C library function - fgets()
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
- str -- This is a pointer to a character array that stores the string to be read.
- n -- The maximum number of characters to read (including the final null character). Usually the length of the array passed as str is used.
- stream -- This is a pointer to a FILE object that identifies the stream from which characters are to be read.
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 -