C Program to Read the Content of file using fgets

C Program to Read the Content of file using fgets.




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.

Following is the declaration for fgets( ) function.
             
char *fgets(char *str, int n, FILE *stream)

str - This is the pointer to an array of chars where the string read is stored.

n - This is the maximum number of characters to be read.

stream - This is the pointer to a FILE object that identifies the stream where characters are read from.

The function returns the same str parameter.

--------------------------------------------------------------------------------------------------------------------------

#include<stdio.h>
#include<stdlib.h>
void main( )
{
    FILE *fp;
    char str[80], fname[50];
    printf("Enter the file name: ");
    scanf("%s", fname);
    if((fp = fopen(fname,"r")) == NULL)
    {
        printf("Cannot open file");
        exit(1);
    }
     while(!feof(fp))
     {
         fgets(str,79,fp);
         printf("%s",str);
     }
    fclose(fp);
}

--------------------------------------------------------------------------------------------------------------------------

Output

--------------------------------------------------------------------------------------------------------------------------

Enter the file name : program.txt
C Programming Language



EmoticonEmoticon