May 6, 2021

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




Share This:    Facebook Twitter

0 comments:

Post a Comment

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