Запись и чтение объекта класса в двоичном файле C ++ - PullRequest
0 голосов
/ 29 мая 2020

Мне пришлось создать программу, которая записывает и читает из двоичного файла данные, хранящиеся в классе. Проблема в том, что я сделал что-то не так, потому что он неправильно записал данные в файл, поэтому из-за этого он также не может его прочитать. Я думаю, что я написал это неправильно, когда пытался записать объект в файл , но я не знаю, как это сделать по-другому. Вот файл заголовка:

#include<iostream>
#include<fstream>
using namespace std;

class Agenda
{
protected:
    char* name = new char[25];
    char* city = new char[25];
    char* number = new char[25];
public:
    Agenda() {} //explicit empty constructor

    //setters
    void set_Name(char* n)
    {
        strcpy_s(name,25, n);
    }
    void set_City(char* c)
    {
        strcpy_s(city,25, c);
    }
    void set_Phone(char* pn)
    {
        strcpy_s(number,25, pn);
    }
    //getters
    char* get_Name()
    {
        return name;
    }
    char* get_City()
    {
        return city;
    }
    char* get_Phone()
    {
        return number;
    }
    ~Agenda() //destructor
    {
        delete[]name;
        delete[]city;
        delete[]number; //eliberating all the allocated memory
    }

    friend ostream& operator<<(ostream& output, Agenda ob);
    friend istream& operator>>(istream& input, Agenda ob);
};

ostream& operator<<(ostream& output, Agenda ob) //overlading extraction 
{
    output << "Name: " << ob.name << ", city: " << ob.city << ", phone number: " << ob.number;
    return output;
}
istream& operator>>(istream& input, Agenda ob) //overloading insertion
{
    input >> ob.name >> ob.city >> ob.number;
    return input;
}

Я перегрузил операторы << и >>, потому что так говорится в задаче, и мне тоже нужно их использовать, но мне не удалось использовать перегруженный оператор извлечения.

Исходный файл:


#include"Header.h"

int main() //read file name from KBD
{
    Agenda ob;
    string filename;
    cout << "Name of file:"; //entering the file's name from KBD
    cin >> filename;
    filename.append(".txt"); //giving the extension to the file's name

    ofstream wfile;
    cout << "Enter the data from agenda(name,city,phone nr): ";
    cin >> ob; //getting the data

    wfile.open(filename, ios::out|ios::binary); //open file to write in it
    if (!wfile)
    {
        cout << "File can't be opened!";
        exit(1);
    }
    else
        cout << "File created" << endl;
    wfile.write((char*)&ob, sizeof(ob)); //write the data from the object into file
    wfile.close(); //closing file

    ifstream rfile;
    rfile.open(filename, ios::in|ios::binary); //opening the file to read from it
    if (!rfile)
    {
        cout << "File can't be opened!";
        exit(1);
    }
    cout << "The file contains:";
    rfile.read((char*)&ob, sizeof(ob)); //reading the object's data from the file
    rfile.close(); //closing file

    return 0;

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...