• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
November 10, 2022 |1.2K Views
C++ program to create Binary File from the existing Text File
Description
Discussion

In this video, we will see how to create a binary file from the existing text file. So there are two types of files- text files and binary files.

Generally, a binary file can be created only from within a program and its contents can be read only by a program.

The task is to read data from a text file and create a new double train containing the same data in binary form.

For example, there are details of students in a file named “Studentdata.txt ” and the task is to produce a binary file named “ Studentdb ” by reading data from the text file “Studentdata.txt ”.

  • Each line of the file “Studentdata.txt ” contains a record of one pupil’s information.
  • A record has 3 attributes i.e., Student, ID, Name, and Age.
  • Each record has a fixed length.

Let us assume that “Studentdata.txt ” has the following data:

Student_ID      Name       Age
1                        Amay         22
2                        Neha         21
3                        Preeti        22

So the record size, the number of bytes in a record = B. However, the file will contain 3 × B bytes, If data for 3 students is written to a disk file. Also, the student’s information can be directly read, If there is information about the student record’s relative position “ pos ” in the file, and pos *( B – 1) will be the record’s starting byte position.


Output:

The size of the record is: 10

  1. Student number 1 has data 1 Amay 22
  2. student number 2 has data 2 Neha 21
  3. student number 3 has data 3 Preeti 22

Data from the file read and printed
Database created for student info
Total records are written in 3.

So, There were 3 records in the file “studentdata.txt ” that were read, printed, and saved in the “ studentdb ” file in binary mode. The text file contains 3 fields in every line- student ID, Name, and Age.

The first line of the text file contains:

1 Amay 22

Create Binary file from existing text file:
https://www.geeksforgeeks.org/how-to-create-binary-file-from-the-existing-text-file/

Read More