How to create Binary File from the existing Text File?
Last Updated :
21 Jul, 2021
In this article, we will discuss how to create a binary file from the given text file. Before proceeding to the steps, let's have an introduction of what are text files and binary files.
Text files: Text files store data in human-readable form 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, audio, text, etc.
Problem Statement: The task here is to read data 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 one customer’s information.
- A record has 3 attributes i.e., ID, Name, and Age.
- Each record has a fixed length.
Let us assume that “Custdata.txt” has the following data-
ID | Name | Age |
---|
1 | Annil | 22 |
2 | Ram | 45 |
3 | Golu | 25 |
- Let the record 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, then the customer's information can be directly read.
- pos* (B - 1) will be the record's starting byte position.
There is no requirement, as such, to store all values in a record in text format. The internal format can be used to directly store values. An option that is good and can be taken as a choice is to define a structure for our record.
struct Customers
{
int ID;
char name[30];
int age;
}
The individual elements of structure customers can now be accessed by creating a structure variable cs as:
- cs.ID.
- cs.name.
- cs.age.
Let us look 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() function is used to read the text file containing the customer data.
Syntax:
int fscanf(FILE* streamPtr, const char* formatPtr, ...);
This function reads the data from file stream and stores the values into the respective variables.
Parameters of fscanf():
- streamPtr: It specifies the pointer to the input file stream to read the data from.
- formatPtr: Pointer to a null-terminated character string that specifies how to read the input. It consists of format specifiers starting with %. Example: %d for int, %s for string, etc.
There is a need to include <cstdio> header file for using this function.
Writing: fwrite() function is used in the program to write the data read from the text file to the binary file in binary form.
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: Pointer to the block of memory whose content is written (converted to a const void*).
- size: The size in bytes of each object to be written.
- count: The count of total objects to be read.
- ptr_OutputStream: Pointer to a file specifying the output file stream to write to.
There is a need to include<cstdio> header file for using this function.
Algorithm: Below is the approach for the program for reading the text file and writing the content in the binary form 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 set 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++
// C++ program for the above approach
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
// Creating a structure for customers
struct Customers {
int ID;
char name[30];
int age;
};
// Driver Code
int main()
{
struct Customers cs;
int rec_size;
rec_size = sizeof(struct Customers);
cout << "Size of record is: "
<< rec_size << endl;
// Create File Pointers fp_input for
// text file, fp_output for output
// binary file
FILE *fp_input, *fp_output;
// Open input text file, output
// binary file.
// If we cannot open them, work
// cannot be done, so return -1
fp_input = fopen("custdata.txt", "r");
if (fp_input == NULL) {
cout << "Could not open input file"
<< endl;
return -1;
}
fp_output = fopen("Customerdb", "wb");
if (fp_output == NULL) {
cout << "Could not open "
<< "output file" << endl;
return -1;
}
// Read one line from input text file,
// into 3 variables id, n & a
int id, a;
char n[30];
// Count for keeping count of total
// Customers Records
int count = 0;
cout << endl;
// Read next line from input text
// file until EOF is reached
while (!feof(fp_input)) {
// Reading the text file
fscanf(fp_input, "%d %s %d ",
&id, n, &a);
// Increment the count by one
// after reading a record
count++;
// Structure variable cs is set
// to values to elements
cs.ID = id, strcpy(cs.name, n), cs.age = a;
// Write the structure variable
// cs to output file
fwrite(&cs, rec_size, 1, fp_output);
printf(
"Customer number %2d has"
" data %5d %30s %3d \n",
count, cs.ID,
cs.name, cs.age);
}
cout << "Data from file read"
<< " and printed\n";
cout << "Database created for "
<< "Customers info\n";
// Count contains count of total records
cout << "Total records written: "
<< count << endl;
// Close both the files
fclose(fp_input);
fclose(fp_output);
return 0;
}
Output:
Size of record is: 40
Customer number 1 has data 1 Annil 22
Customer number 2 has data 2 Ram 45
Customer number 3 has data 3 Golu 25
Data from file read and printed
Database created for Customers info
Total records written: 3
Explanation: 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 first line of the text file contains-
1 Annil 22
This line is read from the file, i.e, the data of ID, Name, and Age are read and their values are assigned to the variables id, n, and a respectively. Now assign the values of these 3 variables to the data 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 mode).
This procedure continues for all the lines of text files until the end of the file is reached. After the execution of the program ends, the file "custdata.txt" will remain as it is, as it was opened in the read mode-
1 Annil 22
2 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 have the contents in binary form, which is not readable. The file, when opened normally, looks like this :
Similar Reads
How to Read From a File in C++?
Reading from a file means retrieving the data stored inside a file. C++ file handling allows us to read different files from our C programs. This data can be taken as input and stored in the program for processing. Generally, files can be classified in two types:Text File: Files that contains data i
4 min read
C++ Program to Append a String in an Existing File
Here, we will build a C++ program to append a string in an existing file using 2 approaches i.e. Using ofstreamUsing fstreamC++ programming language offers a library called fstream consisting of different kinds of classes to handle the files while working on them. The classes present in fstream are
2 min read
C++ program to append content of one text file to another
Given source and destination text files. Append the content from the source file to the destination file and then display the content of the destination file.Example : Input : file.txt : "geeks", file2.txt : "geeks for" Output: file2.txt : "geeks for geeks" Method 1:Approach: Open file.txt in inputs
3 min read
C++ Program to Read Content From One File and Write it Into Another File
Here, we will see how to read contents from one file and write it to another file using a C++ program. Let us consider two files file1.txt and file2.txt. We are going to read the content of file.txt and write it in file2.txt Contents of file1.txt: Welcome to GeeksForGeeks Approach: Create an input f
2 min read
C++ Program to Copy the Contents of One File Into Another File
Here, we will see how to develop a C++ program to copy the contents of one file into another file. Given a text file, extract contents from it and copy the contents into another new file. After this, display the contents of the new file. Approach:Open the first file which contains data. For example,
2 min read
How to Read a File Character by Character in C++?
In C++, file handling is used to store data permanently in a computer. Using file handling we can store our data in secondary memory (Hard disk). In this article, we will learn how to read a file character by character in C++. Example: Input: "Geeks for Geeks"Output: G e e k s f o r G e e k sRead Te
2 min read
C++ Program to Create a Temporary File
Here, we will see how to create a temporary file using a C++ program. Temporary file in C++ can be created using the tmpfile() method defined in the <cstdio> header file. The temporary file created has a unique auto-generated filename. The file created is opened in binary mode and has access m
2 min read
C++ Program to Create a File
Problem Statement:Write a C++ program to create a file using file handling and check whether the file is created successfully or not. If a file is created successfully then it should print "File Created Successfully" otherwise should print some error message. Approach:Declare a stream class file and
2 min read
How to Open and Close a File in C++?
In C++, we can open a file to perform read and write operations and close it when we are done. This is done with the help of fstream objects that create a stream to the file for input and output. In this article, we will learn how to open and close a file in C++. Open and Close a File in C++ The fst
2 min read
How to Redirect cin and cout to Files in C++?
In C++, we often ask for user input and read that input using the cin command and for displaying output on the screen we use the cout command. But we can also redirect the input and output of the cin and cout to the file stream of our choice. In this article, we will look at how to redirect the cin
2 min read