C Library Function - fgets()
C Standard Library - <stdio.h>
Description
The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end of the file is reached, whichever comes first.
Declaration
Here is the declaration for the fgets() function.
char *fgets(char *str, int n, FILE *stream)
Parameters
str -- This is a pointer to an array of chars where the string read is stored.
n -- This is the maximum number of characters to be read (including the final null-character). Usually, the length of the array passed to 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
On success, the function returns the same str parameter. If the end-of-file is encountered and no characters have been read, the contents of str remain 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.
#include <stdio.h>
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 the contents to stdout */
puts(str);
}
fclose(fp);
return(0);
}
Assuming we have a text file file.txt, its content is as follows. The file will serve as input for the example:
We are in 2014
Let's compile and run the above program, this will produce the following result:
We are in 2014