简体   繁体   中英

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() .

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?

So far, the relevant part of my readData looks like this:

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.

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. returnX and returnY are not pointed at the local variables. In the code above, the assignment changes mainx and 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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