fgets() function in C

The syntax of the fgets() function is:

Syntax: char *fgets(char *str, int n, FILE *fp);

The function reads a string from the file pointed to by fp into the memory pointed to by str. The function reads characters from the file until either a newline ('\n') is read or n-1 characters is read or an end of file is encountered, whichever occurs first. After reading the string it appends the null character ('\0') to terminate the string. On success, it returns a pointer to str. On error or end of the file it returns NULL.

The following program demonstrates how to use fgets() function.

#include<stdio.h>
#include<stdlib.h>

int main()
{
    char str[50];
    FILE *fp;
    fp = fopen("myfile2.txt", "r");

    if(fp == NULL)
    {
        printf("Error opening file\n");
        exit(1);
    }

    printf("Testing fgets() function: \n\n");
    printf("Reading contents of myfile.txt: \n\n");

    while( fgets(str, 30, fp) != NULL )
    {
        puts(str);
    }

    fclose(fp);

    return 0;
}

Expected Output:

Testing fgets() function:

Reading contents of myfile.txt:

The first lineSecond lineThis
is thirdand this is fourth

How it works

In line 6, an array of characters str of size 50 is declared.

In line 7, a structure pointer variable fp of type struct FILE is declared.

In line 8, fopen() function is called with two arguments namely "myfile2.txt" and "r". On success, it returns a pointer to file myfile2.txt and opens the file "myfile.txt" in read-only mode. On failure or end of file, it returns NULL.

In lines 10-14, if statement is used to test the value of fp. If it is NULL, printf() statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement.

In line 16 and 17, two printf() statements string "Testing fgets() function: \n\n" and "Reading contents of myfile.txt: \n\n"  to the console.

In lines 19-22, a while loop is used to read the contents of the myfile2.txt. Here is how while loop works:

The function fgets() is called with an argument of 30, so it reads 29 characters from the file, stores them in the array str by appending null character at the end. Then the puts() function is called to display the contents of the str . The puts() function prints the string to the console by converting null character ('\0') at the end of the string to a newline ('\n') character. This is the reason why newline is printed after each iteration. In the second iteration fgets() encounters end of file after reading 27  characters. The puts() function is called again to print these 27 characters along with newline ('\n') at the end. The fgets() function is called again for the third time, but since there are no more characters left to read it returns NULL, the while condition becomes false and control comes out of the while loop.

In line 24, fclose() function is used to close the file pointer to myfile2.txt.

Difference between fgets() and gets()

gets() reads the input from standard input while fgets() reads from the file. Apart from this the most important difference is this:

When gets() reads the input from standard input it converts the newline ('\n') to the null character ('\0') on the other hand when fgets() reads newline ('\n') character from the file it doesn't convert it into null character ('\0'), it is retained as it is.