Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I know how to read and write a complete struct with fstream. But just for curiosity, is there a way to access (read or write) a variable directly? I have never seen somebody doing this.

aStruct * dummyStruct = 0;
int num = 7;

File.seekp(streamPosition, ios::beg);
File.seekp((unsigned long long)&(dummyStruct->aVariable), ios::cur);

File.write(reinterpret_cast<const char*>(&num), sizeof(num));

Has anybody done something like this?

share|improve this question
    
I would recommend using offsetof instead for the seekp call, but it's certainly doable. And if you only want to write that single variable (and the variable is the exact same size as in the structure) then I see no problem with this. – Joachim Pileborg May 26 '13 at 18:25

You can use offsetof to determine the offset location of the variable.

File.seekp(offsetof(aStruct, aVariable), ios::cur);
share|improve this answer
    
And the pointer? It looks weired for me to make a null pointer and take a sub pointer of it. It works of course. – Granini May 26 '13 at 18:45
    
Sorry, I missed you were assigning a null pointer value. All you need to change is the line that does the seek then read into num. – Captain Obvlious May 26 '13 at 18:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.