Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ fstream直接访问结构变量_C++_Struct_Fstream - Fatal编程技术网

C++ fstream直接访问结构变量

C++ fstream直接访问结构变量,c++,struct,fstream,C++,Struct,Fstream,我知道如何用fstream读写完整的结构。但出于好奇,有没有办法直接访问(读或写)变量?我从未见过有人这样做 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 ch

我知道如何用fstream读写完整的结构。但出于好奇,有没有办法直接访问(读或写)变量?我从未见过有人这样做

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));
aStruct*dummyStruct=0;
int num=7;
seekp(streamPosition,ios::beg);
seekp((unsigned long)和(dummyStruct->aVariable),ios::cur;
write(reinterpret_cast(&num),sizeof(num));

有人这样做过吗?

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

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

我建议在
seekp
调用中使用,但这肯定是可行的。如果你只想写一个变量(这个变量和结构中的变量大小完全一样),那么我认为这没有问题。指针呢?对我来说,创建一个空指针并获取它的子指针看起来很奇怪。它当然可以工作。对不起,我错过了您分配的空指针值。您需要更改的只是执行搜索的行,然后将其读入
num