C File I/O Operations : fgets()

The fgets() function is used to reads strings data from a file. Also note that it reads the strings line by line. The basic syntax of function is :
 int fputs(char *str, int n, FILE *fp);
Where str is a character string pointer where the data is stored and n spcifies the size of the character string, fp is file pointer to input stream. On success the function will return non-negative value and on error it returns EOF. 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.

In C programs fgets() implemented as :
 fgets (buffer, size, fp);
C Example Program :
#include <stdio.h>

int main() {
  char str[50];
  FILE *fp;
  fp = fopen("myfile.txt", "r");
  if(fp == NULL) {
    printf("Error opening file.\n");
    return -1;
  // read and prints data line by line
  while((fgets(str, 50, fp)) != NULL) {
    printf("%s", str);

  return 0;
Output :

Hello world, This is Sample Text.
This is the Test String.
This is Just Another Line.

The above code will open the file myfile.txt and prints its content.

Topics :