Write the Binary File While Still Reading From the Text File

In this article, we volition discuss how to create a binary file from the given text file. Before proceeding to the steps, let'due south have an introduction of what are text files and binary files.

Text files : Text files shop data in man-readable grade and sequentially.

Binary files : Binary files store data in the form of bits/groups of bits (bytes) in sequence. These bits' combinations can refer to custom data. Binary files can store multiple types of data, such as images, sound, text, etc.

Problem Statement: The chore here is to read information from a text file and create a new binary file containing the same data in binary form.

Example: Suppose there are details of customers in a file named "Custdata.txt" and the task is to create a binary file named "Customerdb" by reading data from the text file "Custdata.txt".

  • Each line of file "Custdata.txt" contains a record of ane customer's information.
  • A record has 3 attributes i.due east., ID, Name, and Age.
  • Each record has a stock-still length.

Permit united states assume that "Custdata.txt" has the post-obit data-

ID Name Age
ane Annil 22
two Ram 45
3 Golu 25
  • Let the tape size, the number of bytes in a record = B.
  • If data for 3 customers is written to a disk file, then the file will contain 3 × B bytes.
  • If there are information about the customer record's relative position "pos" in the file, and then the customer's information can be direct read.
  • pos* (B – 1) will exist the record's starting byte position.

At that place is no requirement, as such, to shop all values in a record in text format. The internal format can be used to directly shop values. An selection that is good and can be taken equally a choice is to define a structure for our record.

struct Customers  {     int ID;     char name[30];     int age; }

The individual elements of construction customers tin now exist accessed by creating a structure variable cs as:

  1. cs.ID.
  2. cs.name.
  3. cs.historic period.

Let us wait at the methods that would be required to read the text file and write in the binary file. The function required for reading is fscanf() and for writing is fwrite().

Reading: fscanf() office is used to read the text file containing the customer data.

Syntax:

int fscanf(FILE* streamPtr, const char* formatPtr, …);
This role reads the information from file stream and stores the values into the respective variables.

Parameters of fscanf():

  • streamPtr: Information technology specifies the arrow to the input file stream to read the data from.
  • formatPtr: Pointer to a cipher-terminated character string that specifies how to read the input. It consists of format specifiers starting with %. Example: %d for int, %due south for string, etc.

At that place is a need to include <cstdio> header file for using this function.

Writing: fwrite() function is used in the programme to write the data read from the text file to the binary file in binary course.

Syntax:

size_t fwrite(const void * bufPtr, size size, size_t count, FILE * ptr_OutputStream);
The fwrite() function writes "count" number of objects, where size of every object is "size" bytes, to the given output stream.

Parameters of write():

  • bufPtr: Arrow to the cake of memory whose content is written (converted to a const void*).
  • size: The size in bytes of each object to exist written.
  • count: The count of full objects to exist read.
  • ptr_OutputStream: Arrow to a file specifying the output file stream to write to.

There is a demand to include<cstdio> header file for using this part.

Algorithm: Beneath is the approach for the program for reading the text file and writing the content in the binary grade to a binary file.

  • Open the input text file and the output binary file.
  • Until the end of the text file is reached perform the following steps:
    • Read a line from the input text file, into 3 variables using fscanf().
    • The structure variable is gear up to values for elements(to write the structure variable into the output file.
    • Write that structure variable to the output binary file using fwrite().
  • Close the input text file and the output binary file.

Below is the C++ program for the above approach:

C++

#include <cstdio>

#include <cstring>

#include <iostream>

using namespace std;

struct Customers {

int ID;

char proper name[30];

int age;

};

int master()

{

struct Customers cs;

int rec_size;

rec_size = sizeof ( struct Customers);

cout << "Size of tape is: "

<< rec_size << endl;

FILE *fp_input, *fp_output;

fp_input = fopen ( "custdata.txt" , "r" );

if (fp_input == NULL) {

cout << "Could not open input file"

<< endl;

return -ane;

}

fp_output = fopen ( "Customerdb" , "wb" );

if (fp_output == NULL) {

cout << "Could not open "

<< "output file" << endl;

render -1;

}

int id, a;

char n[30];

int count = 0;

cout << endl;

while (! feof (fp_input)) {

fscanf (fp_input, "%d %due south %d " ,

&id, n, &a);

count++;

cs.ID = id, strcpy (cs.name, due north), cs.age = a;

fwrite (&cs, rec_size, 1, fp_output);

printf (

"Customer number %second has"

" data %5d %30s %3d \northward" ,

count, cs.ID,

cs.proper noun, cs.age);

}

cout << "Data  from file read"

<< " and printed\n" ;

cout << "Database created for "

<< "Customers info\n" ;

cout << "Total records written: "

<< count << endl;

fclose (fp_input);

fclose (fp_output);

return 0;

}

Output:

Size of tape is: 40  Client number  i has data     1                    Annil  22 Customer number  2 has data     2                      Ram  45 Customer number  3 has information     three                    Golu  25           Information  from file read and printed Database created for Customers info      Total records written: three

Caption: There were 3 records in the file "custdata.txt" that were read, printed, and saved in the "Customerdb" file in binary mode.
The text file contains 3 fields in every line- ID, Name, and Age.
The beginning line of the text file contains-

          1                    Annil  22

This line is read from the file, i.eastward, the data of ID, Proper noun, and Age are read and their values are assigned to the variables id, northward, and a respectively. At present assign the values of these 3 variables to the information members:  ID, name[], and age of the structure variable cs respectively.
Now using fwrite(&cs, rec_size, 1, fp_output), write one cs object of size rec_size  to the binary file- " fp_output" (binary way).
This procedure continues for all the lines of text files until the terminate of the file is reached. Afterward the execution of the program ends, the file "custdata.txt" volition remain as it is, as it was opened in the read fashion-

          1                         Annil  22  two                           Ram  45  3                          Golu  25

This data is read line by line and written to the file "Customerdb" in binary mode. The file "Customerdb" will take the contents in binary grade, which is non readable. The file, when opened normally, looks similar this :


hatcherhiserfuld1949.blogspot.com

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

0 Response to "Write the Binary File While Still Reading From the Text File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel