Programming with C

⌘K
  1. Home
  2. Docs
  3. Programming with C
  4. File Processing
  5. File Processing Operation...
  6. Read data from file

Read data from file

  • reads data from the given stream into the array pointed to, by ptr.
  • Function fread transfers a specified number of bytes from the location in the file specified by the file position pointer to an area in memory beginning with a specified address. N

Syntax

fread
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)

Parameters

  • ptr âˆ’ This is the pointer to a block of memory with a minimum size of size*nmemb bytes.
  • size âˆ’ This is the size in bytes of each element to be read.
  • nmemb âˆ’ This is the number of elements, each one with a size of size bytes.
  • stream − This is the pointer to a FILE object that specifies an input stream.

Return Value

The total number of elements successfully read are returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, then either an error had occurred or the End Of File was reached.

Program: reading data from file using fread

#include <stdio.h>
#include<stdlib.h>
struct marks
{
 int m1, m2,m3,m4,m5;
};
int main()
{
 int n;
 struct marks m;
 FILE *fptr;
 if ((fptr = fopen("mark.bin","rb")) == NULL){
 printf("Cannot Open File !");
 exit(1);
 }
 printf("Marks are\n");
 for(n = 1; n <= 5; ++n)
 {
 fread(&m, sizeof(struct marks), 1, fptr); 
 printf("Student %d Marks : English: %d\t Maths : %d\t Physics: %d\t Chemistry : %d\t Python: %d\n",n, m.m1, m.m2, m.m3,m.m4,m.m5);
 }
 fclose(fptr); 
 return 0;
}

Output

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments