mardi 17 novembre 2020

How to create a valid write to a binary file

I have created student data to be stored in a binary file but this file is completely broken.

What am I doing wrong?

there was no problem with the text file stored in the notepad.

now after entering after starting the program, it only writes this: & Ô LC_CTYPE = C; LC_M0 & Ô RIC = C; LC_TIME = C

Is there someone able to help me with this? Have a nice day:)

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>



using namespace std;



struct Student{
    string imie;
    string nazwisko;
    int nrAlbumu;
    int wiek;
    float srOcen;
} dane;




int main(){



Student dane;

cout << "Podaj imie:" << endl;
cin >> dane.imie;
cout << "Podaj nazwisko:" << endl;
cin >> dane.nazwisko;
cout << "Podaj nrAlbumu:" << endl;
cin >> dane.nrAlbumu;
cout << "Podaj wiek:" << endl;
cin >> dane.wiek;
cout << "Podaj srednia ocen:" << endl;
cin >> dane.srOcen;


cout << "Student " << dane.imie  <<" "<< dane.nazwisko << " o numerze albumu: " << dane.nrAlbumu << " ma lat " << dane.wiek << " ma srednia ocen rowna: " << dane.srOcen << endl;


1. ----------------writing to the file starts here-----------------------------------------

ofstream ofs("dane.bin", ios::binary);

Student* student = new Student;

student->imie;
student->nazwisko;
student->nrAlbumu;
student->wiek;
student->srOcen;

ofs.write((char*)(student), sizeof(Student));
ofs.close();

 delete student;

2. -----------------reading starts here ----------------------------------------

ifstream ifs("dane.bin", ios::binary);

char* temp = new char[sizeof(Student)];
ifs.read(temp, sizeof(Student));

Student* student2 = (Student*)(temp);

cout << "Student " << dane.imie  <<" "<< dane.nazwisko << " o numerze albumu: " << dane.nrAlbumu << " oraz ma lat " << dane.wiek << " ma srednia ocen rowna: " << dane.srOcen <<"  Potwierdzenie do zapisu i odczytu!" << endl;

delete student;




    return 0;
}

Aucun commentaire:

Enregistrer un commentaire