0

I have the following case study:

The variable "x_y" holds the content of a file in binary mode, read as follows:

std::string x_y;

std::ifstream fnb(fn, std::ios::in | std::ios::binary);
std::stringstream file_jh;
file_jh << fnb.rdbuf();
x_y = file_jh.str();

What I'm trying to do is to read/copy an std::uint32_t value from x_y, do some computation on it, and saving it back at the same address as follows:

std::uint32_t delta = 0x00012345;
std::uint32_t temp_val = 0;

for (size_t i = 0; i < x_y.size(); i += 4)
{

    x_y.copy((char*)&temp_val, sizeof(std::uint32_t), i);

    temp_val -= delta;

    delta += 20;

    x_y.replace(i, sizeof(std::uint32_t), (char*)&temp_val);
}

The problem I'm having is that it works only for the first dword value, but for the rest of the data its producing incorrect results. Additionally, it seems to be messing up the offsets too, which I don't understand why!

Could you please share any suggestions you might have, either by improving on above code or something different.

Thank you.

Xigma
  • 177
  • 1
  • 11
  • In what format is the value stored in the file? In hexadecimal representation using ascii characters? In base-2 representation using ascii characters? In machine format with little endian ordering of bytes, but with most significant bit first? – KamilCuk Nov 23 '19 at 19:04
  • Format is binary. I'm reading an executable file. – Xigma Nov 23 '19 at 19:06
  • Yes, I'm casting it to (char*) to read one byte a time from the file. – Xigma Nov 23 '19 at 19:09
  • 1
    Use `x_y.replace(i, sizeof(std::uint32_t), (char*)&temp_val, sizeof(std::uint32_t));` to avoid surprises with zero-terminated strings. Also, make sure that x_y.size() is divisible by 4. – Kit. Nov 23 '19 at 19:09
  • @Xigma if the file is binary, why are you reading it into a `std::string` at all? Why not simply read the `uint32_t` directly from the `std::ifstream`? – Remy Lebeau Nov 23 '19 at 20:04
  • You're right, this is a mistake I made at the beginning of the project. I thought it'd be easier to go with std::string instead! – Xigma Nov 23 '19 at 20:58

0 Answers0