简体   繁体   中英

Binary file I/O in C++

I've written a code to store student info to a binary file and also get the informations as required. But I'm not getting the desired output. When I'm trying to read a student info from the student.bin file the name field is always showing NULL and the roll field is the last entered roll number. What's going wrong here ?

#include <bits/stdc++.h>
using namespace std;

class student{
public:
    string name;
    int roll;
};


int main(){
    fstream file("student.bin", ios::in | ios::out | ios::binary);
    int written = 0;
    while(1){
        int choice;
        student a;
        int i;
        cout << "0. Exit\n1. Write\n2. Read\nEnter Choice : ";
        cin >> choice;
        switch(choice){
            case 1:
                cout << "Enter name & roll : ";
                cin >> a.name >> a.roll;
                cout << "You entered " << a.name << " " << a.roll << endl;
                cout << "Enter the index : ";
                cin >> i;
                if(i > written){
                    cout << "This index doesnt exist !" << endl;
                    break;
                }
                file.seekp(i * sizeof(student), ios::beg);
                file.write((char*) &a, sizeof(student));
                written++;
                break;
            case 2:
                cout << "Enter index : ";
                cin >> i;
                file.seekg(i * sizeof(student), ios::beg);
                file.read((char*) &a, sizeof(student));
                cout << "Name : " << a.name << " Roll : " << a.roll << endl;
                break;
            case 0:
                exit(0);
            default:
                cout << "Wrong Choice !" << endl;
                break;
        }
    }
    file.close();
}
file.write((char*) &a, sizeof(student));

I'm sure that when you were taught sizeof () in class, you were told that it returns the size of the structure, which is a constant value.

Your student structure contains a std::string , which is a text string of unlimited length. Ask yourself how would it be possible for sizeof () to return a relatively small value for this short structure, on the order of a dozen bytes, or so, whether it contains a short string of a few characters, or a few megabytes.

A std::string , or any other class, is a binary structure. The actual text isn't a part of the string. The std::string class dynamically allocates memory for the text string it holds, and maintains internal pointers to the dynamically allocated memory.

Writing the binary values of those pointers, here, to a file accomplishes nothing useful. When read in subsequently, chances are that they would be pointers to memory that no longer exists.

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