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)

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

#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