tags:

views:

87

answers:

2

Hi,

I have the contents of a file assigned into a string object. For simplicity the file only has 5 bytes, which is the size of 1 integer plus another byte. What I want to do is get the first four bytes of the string object and somehow store it into a valid integer variable by the program. Then the program will do various operations on the integer, changing it. Afterward I want the changed integer stored back into the first four bytes of the string object.

Could anyone tell me I could achieve this? I would prefer to stick with the standard C++ library exclusively for this purpose. Thanks in advance for any help.

A: 

If you are reading into std::string from that file any zero byte would signal end of the string, so you might end up with a string that is shorter then 5 bytes. Take a look here for how to do binary I/O with C++ streams.

Nikolai N Fetissov
I can verify that the string object I am working with is the correct size as the file, even with a zero byte in it. On the site you linked, on the section about reading data it uses myFile.read (buffer, 100); with myFile being an ifstream object and buffer being a char array. I want to read the first four bytes as a regular int variable, not a char array.
kaykun
Get further to "Reading/writing non-character data". Just read into your int, without intermediate string.
Nikolai N Fetissov
+2  A: 
Pestilence
kaykun
Please note that casting any memory address to larger types may give you cpu alignment faults. It's ok on x86 processesors because they allow you to do it, but pretty much all other processors will generate a alignment fault. If you want your code to be cross-platform you can use memcpy instead of *(int*). e.g. int i; memcpy(
Shane Powell
Thanks for the info, I just got it to work with memcpy as well. I'll use that from now on.
kaykun