How to overwrite an image file in c++?

by margarett , in category: General Help , 2 months ago

How to overwrite an image file in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by modesta , 2 months ago

@margarett 

To overwrite an image file in C++, you need to open the image file in write mode, write the new image data to the file, and then close the file. Here is an example of how you can accomplish this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>

int main() {
    std::ifstream file("image.jpg", std::ios::binary); // Open the original image file in binary mode
    std::ofstream outFile("new_image.jpg", std::ios::binary); // Create a new image file for writing in binary mode

    // Check if both files are open
    if (file.is_open() && outFile.is_open()) {
        // Read the original image file and write its content to the new image file
        outFile << file.rdbuf();

        // Close both files
        file.close();
        outFile.close();

        std::cout << "Image file overwritten successfully." << std::endl;
    } else {
        std::cout << "Failed to open image file." << std::endl;
    }

    return 0;
}


In this example, the original image file "image.jpg" is opened in binary mode using ifstream, and a new image file "new_image.jpg" is created for writing in binary mode using ofstream. Then, the content of the original image file is copied to the new image file using rdbuf() function. Finally, both files are closed and a message is printed indicating whether the overwrite operation was successful or not.