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 write the file using any of the following file modes based on the requirements,
w -> used to open file for writing and new file is created always and assumed that file does not exists.
a -> used to open file for appending and initial position is at the end 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 write and create the binary file based on user input student id, name and mark using file write mode.
student_id, student_name and mark are the user inputs and creates the binary file 'student_mark_list.txt' to store the student mark detail.
#include<stdio.h> struct student { char name[30]; int id, mark; }; void main() { struct student stu; FILE *fp; char ch; do { fp = fopen("student_mark_list.txt", "ab+"); printf("\nEnter student id: "); scanf("%d", &stu.id); printf("\nEnter student name: "); scanf(" %s", stu.name); printf("\nEnter student mark: "); scanf("%d", &stu.mark); fwrite(&stu, sizeof(stu), 1, fp); fclose(fp); printf("\nStudent mark is written successfully!"); printf("\nDo you want to add more, press 'y' otherwise 'n'?"); scanf(" %c", &ch); } while(ch=='y' || ch =='Y'); }
Output:
$ cc binary-file-write.c $ ./a.out Enter student id: 1 Enter student name: student1 Enter student mark: 89 Student mark is written successfully! Do you want to add more, press 'y' otherwise 'n'?y Enter student id: 2 Enter student name: student2 Enter student mark: 67 Student mark is written successfully! Do you want to add more, press 'y' otherwise 'n'?y Enter student id: 3 Enter student name: student3 Enter student mark: 98 Student mark is written successfully! Do you want to add more, press 'y' otherwise 'n'?n
created text file:
$ cat student_mark_list.txt student1p@p@Ystudent2p@p@Cstudent3p@p@b
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page