I try to replace data in binary file using C++ and fstream library. Is it possible to do that with this library? I would like to print 5 bytes of file in address: 0xB03 and change the last of these bytes to 0.
I have written the following code snippet:
int getFileSize(std::string filename)
{
std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
int retVal = in.tellg();
in.close();
return retVal;
}
int main()
{
std::string filename;
std::cout << "Please insert file path." << std::endl;
std::getline(std::cin, filename);
std::cout << "File size is " << getFileSize(filename) << std::endl;
int address = 0xB03;
unsigned int instLen = 5;
char * instToChange = new char[instLen];
std::ifstream input(filename, std::ios::binary);
input.seekg(address);
input.read(instToChange, instLen);
input.close();
std::cout << std::hex << (unsigned int)(instToChange[0] & 0x000000FF) << std::endl;
std::cout << std::hex << (unsigned int)(instToChange[1] & 0x000000FF) << std::endl;
std::cout << std::hex << (unsigned int)(instToChange[2] & 0x000000FF) << std::endl;
std::cout << std::hex << (unsigned int)(instToChange[3] & 0x000000FF) << std::endl;
std::cout << std::hex << (unsigned int)(instToChange[4] & 0x000000FF) << std::endl;
instToChange[4] = (char)0x00;
std::cout << std::hex << (unsigned int)(instToChange[0] & 0x000000FF) << std::endl;
std::cout << std::hex << (unsigned int)(instToChange[1] & 0x000000FF) << std::endl;
std::cout << std::hex << (unsigned int)(instToChange[2] & 0x000000FF) << std::endl;
std::cout << std::hex << (unsigned int)(instToChange[3] & 0x000000FF) << std::endl;
std::cout << std::hex << (unsigned int)(instToChange[4] & 0x000000FF) << std::endl;
std::ofstream output(filename, std::ios::binary);
output.seekp(address);
output.write(instToChange, instLen);
output.close();
system("pause");
return 0;
}
I have tried many versions of this code and I still can't understand why it doesn't work.
User contributions licensed under CC BY-SA 3.0