Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.8 kB
3
Indexable
Never
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>

class Animal {
public:
    virtual std::string move() = 0;
    virtual ~Animal() {}

protected:
    std::string type;
};

class printable {
public:
    virtual std::string to_string() = 0;
    virtual void print() = 0;
    virtual ~printable() {}
};

class bird : public Animal, public printable {
public:
    bird() { type = "bird"; }
    std::string move() override { return "flies"; }
    std::string to_string() override { return type; }
    void print() override { std::cout << type << std::endl; }
};

class dog : public Animal, public printable {
public:
    dog() { type = "dog"; }
    std::string move() override { return "runs"; }
    std::string to_string() override { return type; }
    void print() override { std::cout << type << std::endl; }
};

class rabbit : public Animal, public printable {
public:
    rabbit() { type = "rabbit"; }
    std::string move() override { return "hops"; }
    std::string to_string() override { return type; }
    void print() override { std::cout << type << std::endl; }
};

int main() {
    const int size = 10;
    printable* arr[size];
    for (int i = 0; i < size; i++) {
        int random = rand() % 3;
        if (random == 0)
            arr[i] = new bird();
        else if (random == 1)
            arr[i] = new dog();
        else
            arr[i] = new rabbit();
    }

    for (int i = 0; i < size; i++) {
        arr[i]->print();
        std::cout << arr[i]->to_string() << " " << arr[i]->move() << std::endl;
    }

    // zapis do pliku tekstowego
    std::ofstream text_file("animals.txt");
    for (int i = 0; i < size; i++) {
        text_file << arr[i]->to_string() << " " << arr[i]->move() << std::endl;
    }
    text_file.close();

    // zapis do pliku binarnego
    std::ofstream binary_file("animals.bin", std::ios::binary | std::ios::out);
    for (int i = 0; i < size; i++) {
        binary_file.write(reinterpret_cast<char*>(arr[i]), sizeof(printable));
    }
    binary_file.close();

    // odczyt z pliku binarnego
    std::ifstream binary_file_in("animals.bin", std::ios::binary | std::ios::in);
    printable* arr_in[size];
    for (int i = 0; i < size; i++) {
        arr_in[i] = new bird();
        binary_file_in.read(reinterpret_cast<char*>(arr_in[i]), sizeof(printable));
    }
    binary_file_in.close();

    // wyświetlenie danych odczytanych z pliku binarnego
    for (int i = 0; i < size; i++) {
        arr_in[i]->print();
        std::cout << arr_in[i]->to_string()<< " " << arr_in[i]->move() << std::endl;
}

// zwolnienie pamięci
for (int i = 0; i < size; i++) {
    delete arr[i];
    delete arr_in[i];
}

return 0;