C program to read data from file using fgets() function

In this exercise we will learn how to read data from file using fgets() function... 

EX: Write a C program to read data from file using fgets(), C program to read data from file, How to read content from the file in C.


In previous program we learnt how to read data from file using fgetc(). In this program we will use  fgets() to read content from the file.


Syntax of fgets():

char *fgets(char *str, int n, FILE *stream)


Here, str is the pointer to an array of chars where the string/data is stored, n is the maximum number of characters to be read including the final character null and stream is the pointer to a FILE object that identifies an input stream.




File contains:

  Program to read data from file:


#include<stdio.h>
int main()
{
    FILE *fp;
    char str[100];

    fp = fopen("file.txt""r"); 
    //Read string using fgets()
    fgets(str8,fp);
    printf("%s",str);

    fclose(fp);
    return 0;
    
}

Above Program will show the following output:

Welcome




No comments:

Post a Comment

If you have any doubts, please discuss here...👇