C Tutorial
What is binary file ?
Unformatted data file organises data into blocks containing continuous bytes of information.
Blocks represents the more complex data structures such as arrays of structures.
C programming language provides the built-in functions for file processings.
We can read the binary file using any of the following file modes based on the requirements,
r -> used to open file for reading and position at the start of the file.
r+ -> used to open file for update (both reading and writing), initial position is at the start of the file for reading and writing.
w+ -> used to open file for update (both reading and writing) and new file is created if file does not exists, initial position is at the start of the file for reading and writing
a+ -> used to open file for update (both reading and writing), initial position is at the end of the file for reading and writing.
This c program is used to read the binary file and assign values to structure variable student id, name and mark using file read mode then prints all the records in the file.
student_id, student_name and mark are part of structure variable student and reads the file 'student_mark_list.txt'.
#include<stdio.h> struct student { char name[30]; int id, mark; }; void main() { struct student stu; FILE *fp; fp = fopen("student_mark_list.txt", "ab+"); if(fp == NULL) { printf("\nInvalid binary file!"); } else { printf("\nStudent mark details"); printf("\n---------------------"); printf("\nstudent id\tstudent name\t mark"); while(fread(&stu, sizeof(stu),1,fp)==1) { printf("\n%d\t%s\t%d", stu.id,stu.name,stu.mark); } fclose(fp); } }
Assume binary file 'student_mark_list.txt' content :
$ cat student_mark_list.txt student1p@p@Ystudent2p@p@Cstudent3p@p@b
Output:
$ cc binary-file-read.c $ ./a.out Student mark details --------------------- student id student name mark 1 student1 89 2 student2 67 3 student3 98
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page