File operations- Reading


 Reading from the File

In C programming we can read content of a file by using fscanf()fgets() and fgetc() functions. All these functions are used to read the contents of a file. Let us discuss about those functions one by one :-

1. fscanf() Function

The fscanf() function is used to read character set means strings from the file. It returns EOF (End Of File), when all the content of the file are read by it. IT does not read spaces.

Syntax 

fscanf(FILE *fp, const char string[])

The fscanf() method accepts two arguments or parameters. first one is a pointer of FILE type which is a file pointer and the other one is the string of character in which the characters are stored after reading from the file.

Program Example

#include<stdio.h>

int main()
{
    FILE *fp;

    char str[100];

    fp=fopen("hello.txt", "r");

    while(fscanf(fp,"%s",str)!=EOF)
    {
        printf("%s",str);
    }

    fclose(fp);

    return 0;
}

2. fgets() Function

The fgets() function in C is used to read string from the stream. We can specify the number of characters which we want to read from the file by the fgets() function. Means we can read a string to a particular range of characters by using fgets() function. This method can read the spaces also.

Syntax

fgets(char *string, int length, FILE *fp);

The fgets() function accepts three parameters or arguments which are given below:-

  • char string : It is a string which will store the data after reading from the file.
  • int length : It is an integer which gives the length of string to be considered.
  • FILE *fp : It is the pointer to be opened file or you can say that a file pointer.

Program Example

#include<stdio.h>

int main()
{
    FILE *fp;

    char str[100];

    if(fp=fopen("hello.txt","r"))
    {
        printf("%s", fgets(str, 50, file));
    }

    fclose(fp);

    return 0;
}

3. fgetc() Function 

The fgetc() function in C is used to return a single character from the file. IT gets a character from the file and return EOF at the end of the file. If we want to read only a single character from the file then we can use fgetc() function.

Syntax 

fgetc(FILE *fp)
 
The fgetc() function accepts only a single parameter or argument that is a file pointer.

Program Example

#include<stdio.h>

int main()
{
    FILE *fp;

    char str;

    if(fp=fopen("hello.txt","r"))
    {
        while((str=fgetc(fp))!=EOF)
         {
                printf("%c",str);
          }
     }

    fclose(fp);

    return 0;
}












No comments:

Post a Comment