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;
//-------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;
//-------------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;
}
ofs.write((char*)(student), sizeof(Student));-- This will never work. Types that are not trivially copyable cannot be written to binary files like this. You need to serialize the object, not just write raw bytes to a binary file.Studentobject containsstd::string. That is an object that is not trivially-copyable, thus theStudentclass is not trivially-copyable. If you want more proof, what doessizeofdo? What value does it return? Thesizeofis a compile-time value. Now let's say thatstd::stringhas asize()of 1000 characters. Thesizeofhad no idea how many characters at runtime thestd::stringwill have. Thus that entire line makes no sense and will not work. If youstd::cout << sizeof(Student);what value do you get? I bet it isn't 1000.