[英]C++ read() from ifstream: without pointers?
Suppose I have a struct and a file with binary representations of those structs and I'll make a function/method that access this binary data using ifstream::read()
. 假设我有一个结构和一个带有这些结构的二进制表示形式的文件,我将制作一个函数/方法,使用
ifstream::read()
访问此二进制数据。
Here's an example struct: 这是一个示例结构:
struct MyStruct {
int x; //Value interested in
int y; //Value interested in
int anotherInteger; //Not interested
double aDouble; //Not interested
}
How do I make the function (I'll call it here readData) either: not using pointers when reading or, if using pointers is necessary, where would I put the proper delete? 我该如何制作函数(我在这里将其称为readData):读取时不使用指针,或者,如果有必要使用指针,我应该在哪里放置适当的删除?
So far, the relevant part of my readData looks like this: 到目前为止,我的readData的相关部分如下所示:
void readData(int position, int &returnX, int &returnY) {
ifstream inFile("binaryFile.dat",ios::binary);
MyStruct *st = new MyStruct[1];
inFile.seekg(sizeof(MyStruct)*pos);
inFile.read((char*) st, sizeof(MyStruct));
returnX = st[0].x;
returnY = st[0].y;
//delete [] st goes here?
}
I've tried uncommenting the delete part, but I get an allocation error, probably because the values of x and y are pointing to something that doesn't exist anymore. 我尝试取消删除部分的注释,但出现分配错误,可能是因为x和y的值指向的东西不再存在。
Any ideas on how to solve this? 关于如何解决这个问题的任何想法?
Why wouldn't you use a local variable? 为什么不使用局部变量?
void readData(int position, int &returnX, int &returnY) {
ifstream inFile("binaryFile.dat",ios::binary);
inFile.seekg(sizeof(MyStruct)*position);
MyStruct st;
inFile.read((char*) &st, sizeof(MyStruct));
returnX = st.x;
returnY = st.y;
}
int main() {
int mainx, mainy;
readData(0, mainx, mainy);
return 0;
}
Also, references cannot be re-seated. 同样,引用不能重新建立。 Therefore the assignment assigns the value to the origional
int
passed by the calling function. 因此,赋值将值分配给调用函数传递的原始
int
。 returnX
and returnY
are not pointed at the local variables. returnX
和returnY
没有指向局部变量。 In the code above, the assignment changes mainx
and mainy
. 在上面的代码,分配改变
mainx
和mainy
。
The simpler way it's to use a local variable: 使用局部变量的更简单方法是:
void readData(int position, int &returnX, int &returnY) {
ifstream inFile("binaryFile.dat",ios::binary);
MyStruct st;
inFile.seekg(sizeof(MyStruct)*position);
inFile.read((char*)&st, sizeof(MyStruct));
returnX = st.x;
returnY = st.y;
}
The delete[]
is fine. delete[]
很好。 If you get an error, it's not because the values of x and y are pointing to something that doesn't exist anymore since their values are just integers and don't point to anything. 如果出现错误,这不是因为x和y的值指向不再存在的东西,因为它们的值只是整数并且不指向任何东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.