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