The Wayback Machine - https://web.archive.org/web/20241010194716/https://www.geeksforgeeks.org/cpp-program-to-modify-the-content-of-a-binary-file/
Open In App

C++ program to modify the content of a Binary File

Last Updated : 01 Nov, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This article explains how to modify the content of a Binary File.

Given a binary file that contains the records of students, the task is to modify or alter the record of the specified student. If the record of no such student exists, then print “record not found”.

Examples:

Input:
old roll no: 1
new roll no: 11
new name: "Geek"
Output:
roll no: 11
name: "Geek"
record successfully modified

Input:
old roll no: 234
new roll no: 14
new name: "Geek2"
Output:
record not found

In this example, the existing roll number of the student whose record is to be modified is taken from the user and a newly updated record is created that replaces the previous record.

Approach:

  • Step 1: Searching for the roll number in the binary file.
  • Step 2: While searching in the file, the variable “pos” stores the position of file pointer record then traverse(continue) reading of the record.
  • Step 3: If the roll number to be searched exists then place the write pointer (to ending of the previous record) i.e. at pos.
  • Step 4: Call getdata function to take the new record.
  • Step 5: Write the new object at the position “pos” and hence the record is updated and print “record successfully updated”.
  • Step 6: If the roll number does not exists then print “record not found”.

Standard Library Functions used:

// tells the position of read pointer 
file.tellg();

// places the writing pointer at 
// position "pos" in the file
file.seekp(pos);

Below is the implementation of the above approach:




// C++ program to modify the content
// of a binary file
  
#include <bits/stdc++.h>
using namespace std;
  
class abc {
    int roll;
    char name[20];
  
public:
    void getdata(int, char[]);
    void update(int, int, char[]);
    void testcase1();
    void testcase2();
    void putdata();
};
  
// Code to display the data of the
// data of the object
void abc::putdata()
{
    cout << "roll no: ";
    cout << roll;
    cout << "\nname: ";
    cout << name;
}
  
// Code to set the value to the object
void abc::getdata(int a, char str[])
{
    // setting the new roll no
    roll = a;
  
    // setting new name
    strcpy(name, str);
}
  
void abc::update(int rno, int r, char str[])
{
    // code to update and modify
    // the content of the binary file
    int pos, flag = 0;
  
    // rno=9
    fstream fs;
    fs.open("he.dat",
            ios::in | ios::binary | ios::out);
  
    while (!fs.eof()) {
        // storing the position of
        // current file pointeri.e. at
        // the end of previously read record
        pos = fs.tellg();
  
        fs.read((char*)this, sizeof(abc));
        if (fs) {
  
            // comparing the roll no with that
            // of the entered roll number
            if (rno == roll) {
                flag = 1;
  
                // setting the new (modified )
                // data of the object or new record
                getdata(r, str);
  
                // placing the put(writing) pointer
                // at the starting of the  record
                fs.seekp(pos);
  
                // writing the object to the file
                fs.write((char*)this, sizeof(abc));
  
                // display the data
                putdata();
                break;
            }
        }
    }
    fs.close();
  
    if (flag == 1)
        cout << "\nrecord successfully modified \n";
    else
        cout << "\nrecord not found \n";
}
  
// Sample input 1
void abc::testcase1()
{
    int rno, r;
    char name[20];
  
    // roll no to be searched
    rno = 1;
  
    // new roll no
    r = 11;
  
    // new name
    strcpy(name, "Geek");
  
    // call update function with new values
    update(rno, r, name);
}
  
// Sample input 2
void abc::testcase2()
{
    int rno, r;
    char name[20];
  
    // roll no to be searched
    rno = 4;
  
    // new roll no
    r = 14;
  
    // new name
    strcpy(name, "Geek2");
  
    // call update function with the new values
    update(rno, r, name);
}
  
// Driver code
int main()
{
    abc s;
  
    // sample case 1
    s.testcase1();
  
    // sample case 2
    s.testcase2();
  
    return 0;
}


Output:



Similar Reads

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 file stream object and open file.txt in it.Create a
2 min read
C++program to delete the content of a Binary File
This article explains how to delete the content of a Binary File. Given a binary file that contains the records of students, the task is to delete the record of the specified student. If the record of no such student exists, then print “record not found”. Examples: Input: roll no: 1 Output The deleted record is roll no: 1 name: vinay record success
3 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 inputstream and file2.txt in outputstream with the appen
3 min read
How to create Binary File from the existing Text File?
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 sequ
7 min read
C++ Program to Modify a matrix by rotating ith row exactly i times in clockwise direction
Given a matrix mat[][] of dimensions M * N, the task is to print the matrix obtained after rotating every ith row of the matrix i times in a clockwise direction. Examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output:1 2 36 4 58 9 7Explanation:The 0th row is rotated 0 times. Therefore, the 0th row remains the same as {1, 2, 3}.The 1st r
3 min read
C++ Program to Modify a string by performing given shift operations
Given a string S containing lowercase English alphabets, and a matrix shift[][] consisting of pairs of the form{direction, amount}, where the direction can be 0 (for left shift) or 1 (for right shift) and the amount is the number of indices by which the string S is required to be shifted. The task is to return the modified string that can be obtain
3 min read
C++ Program to Modify given array to a non-decreasing array by rotation
Given an array arr[] of size N (consisting of duplicates), the task is to check if the given array can be converted to a non-decreasing array by rotating it. If it's not possible to do so, then print "No". Otherwise, print "Yes". Examples: Input: arr[] = {3, 4, 5, 1, 2}Output: YesExplanation: After 2 right rotations, the array arr[] modifies to {1,
2 min read
C++ Program to Copy One File into Another File
To copy the text/contents of one file to another file, we should know the basics of reading and writing a text file in C++. To copy the file using C++, we read the contents of the source file and write it into the destination file. Steps to copy one file to another in C++: Create objects of ifstream and ofstream classes.Check if they are connected
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, a file named "file1.txt" contains three strings o
2 min read
Reverse the content of a file and store it in another
The article explains how to store the reverse of the first text file's data to a second text file. In this post, it has been assumed that there is no text in the first text file. So we will write some text in a first text file by passing data to reverse function and then in reverse function we will copy the reverse of its data to another text file.
3 min read
Modify given array to a non-decreasing array by rotation
Given an array arr[] of size N (consisting of duplicates), the task is to check if the given array can be converted to a non-decreasing array by rotating it. If it's not possible to do so, then print "No". Otherwise, print "Yes". Examples: Input: arr[] = {3, 4, 5, 1, 2}Output: YesExplanation: After 2 right rotations, the array arr[] modifies to {1,
10 min read
How to Read Binary Search Tree from File in C++?
A binary search tree is a hierarchical data structure in which for every node in the tree, the value of all nodes in the left subtree is less than the node's value and the value of all nodes in the right subtree is greater than the node's value. This property of the binary search tree makes it efficient for searching, insertion, and deletion operat
4 min read
C++ program to read file word by word
Given a text file, extract words from it. In other words, read the content of file word by word. Example : Input: And in that dream, we were flying. Output: And in that dream, we were flying. Approach : 1) Open the file which contains string. For example, file named "file.txt" contains a string "geeks for geeks". 2) Create a filestream variable to
1 min read
Program to delete a line given the line number from a file
Given a file and a line number n, the task is to delete nth line from the given text file. Suppose the initial content of myfile.txt is : GeeksforGeeks GeeksforGeeks IDE GeeksforGeeks Practice GeeksforGeeks Contribute After Deletion of Line 2 the content would be : GeeksforGeeks GeeksforGeeks IDE GeeksforGeeks Contribute Approach : 1) Open the sour
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 mode "wb+". These temporary files are automatically
2 min read
C++ Program to Make a File Read-Only
Here, we will build C++ Program to Make a File Read-Only using 2 approaches i.e. Using ifstreamUsing 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 ofstream, ifstream, fstream. 1. Using "ifstream"The output of the
2 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 ofstream, ifstream and fstream. The file we are co
2 min read
C++ Program to Count the Number of Spaces in a File
Here, we will see how to count number of spaces in a given file. First, we will read the contents of the file word by word, keep one counter variable 'count', and set it to zero while declaring. Increment 'count' each time you read a single word from the file. Example: Input: Geeks For Geeks Output: There are 2 whitespaces in file Approach:Open the
2 min read
C++ Program to Read and Print All Files From a Zip File
In this article, we will explore how to create a C++ program to read and print all files contained within a zip archive. What are zip files? Zip files are a popular way to compress and store multiple files in a single container. They use an algorithm to decrease the size of the data they store. They also contain information about file type, name, s
3 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 open that text file in writing mode. If the fil
2 min read
Find Content of a Polynomial from its integer coefficients
Given an array arr[] which denotes the integer coefficients of the polynomial, the task is to find the content of the polynomial. Content of polynomials with integer coefficients is defined as the greatest common divisor of its integer coefficients.That is for: F(x) = amxm + am-1xm-1 + ........+a1x + a0Then, Content of Polynomial = gcd(am, am-1, am
4 min read
Recursive Program for Binary to Decimal
Given a binary number as string, find its decimal equivalent. Examples: Input : binary = "101"Output : 5 Input : binary = "1111"Output : 15 We have discussed iterative solution to convert Binary to Decimal.The idea is simple, we add current term and recur for remaining terms. C/C++ Code // Recursive CPP program to convert binary // decimal #include
3 min read
C++ Program to Find Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String
Given a binary string S of size N, the task is to maximize the sum of the count of consecutive 0s present at the start and end of any of the rotations of the given string S. Examples: Input: S = "1001"Output: 2Explanation:All possible rotations of the string are:"1001": Count of 0s at the start = 0; at the end = 0. Sum= 0 + 0 = 0."0011": Count of 0
6 min read
C++ Program for Counting sets of 1s and 0s in a binary matrix
Given a n × m binary matrix, count the number of sets where a set can be formed one or more same values in a row or column. Examples: Input: 1 0 1 0 1 0 Output: 8 Explanation: There are six one-element sets (three 1s and three 0s). There are two two- element sets, the first one consists of the first and the third cells of the first row. The second
2 min read
C++ Program to Check horizontal and vertical symmetry in binary matrix
Given a 2D binary matrix of N rows and M columns. The task is to check whether the matrix is horizontal symmetric, vertical symmetric, or both. The matrix is said to be horizontal symmetric if the first row is the same as the last row, the second row is the same as the second last row, and so on. And the matrix is said to be vertical symmetric if t
4 min read
C++ Program To Add Two Binary Strings
Given two binary strings, return their sum (also a binary string).Example: Input: a = "11", b = "1" Output: "100" We strongly recommend you to minimize your browser and try this yourself first The idea is to start from the last characters of two strings and compute the digit sum one by one. If the sum becomes more than 1, then store carry for the n
3 min read
C++ Program For Binary To Octal Conversion
The problem is to convert the given binary number (represented as a string) to its equivalent octal number. The input could be very large and may not fit even into an unsigned long long int. Examples: Input: 110001110Output: 616 Input: 1111001010010100001.010110110011011Output: 1712241.26633 Simple Approach The idea is to consider the binary input
5 min read
C++ Program For Binary Search
In this article, we will learn about the Binary Search algorithm and how to implement it in a C++ program. Binary Search is a search algorithm that is faster than the linear search algorithm. Binary Search is used to search the position of the target element in a sorted array by repeatedly dividing the search space in half. Binary search eliminates
5 min read
C++ Program To Find Decimal Equivalent Of Binary Linked List
Given a singly linked list of 0s and 1s find its decimal equivalent. Input: 0->0->0->1->1->0->0->1->0 Output: 50 Input: 1->0->0 Output: 4 The decimal value of an empty linked list is considered as 0. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Initialize the result as 0. Traverse
3 min read
C++ Program For Binary To Decimal Conversion
The binary number system uses only two digits 0 and 1 to represent an integer and the Decimal number system uses ten digits 0 to 9 to represent a number. In this article, we will discuss the program for Binary to Decimal conversion in C++. Algorithm to Convert Binary Numbers to DecimalInitialize a variable dec_value to store the decimal representat
4 min read
Article Tags :