here is the code, that reads a file. Currently i am able to print contents of the file but i want to edit its contents. how can i do this?

#include<iostream>
#include<fstream>
using namespace std;
void main()
{

wfstream file;
file.open("hello.exe",ios::binary | ios::in);

if (!file)
{
    cout<<"ERROR"<<endl;
    exit(0);
}

wcout<<file.rdbuf();

}

You must transfer the data into an array (or vector) that you can use to manipulate the data. Then, you save the data back to the file, overwriting it. The rdbuf is really not meant for you to tamper with, and you certainly cannot use it to modify the content of the file. Not to mention that manipulating rdbuf would be very hard since it has basically not useful interface for that, e.g., you won't be able to insert, overwrite, or delete data at random places.

You can use the seekg / tellg facilities to move to certain reading position with the fstream which will allow you to read only the part of the file that is interesting, instead of loading the entire thing in memory. But that is about as far as it goes with manipulating the data using the fstream object. To be able to do more useful (and non-sequential) manipulations, you will need a more powerful random-access container, like std::vector or std::deque.

Alright thanks alot. i think i should start using vector char =)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.