简体   繁体   English

fstream直接访问结构变量

[英]fstream directly access struct variable

I know how to read and write a complete struct with fstream. 我知道如何使用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? 有人做过这样的事情吗?

您可以使用offsetof确定变量的偏移位置。

File.seekp(offsetof(aStruct, aVariable), ios::cur);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM