0
I don't know how type-castings will be done in this problem. I get weird results. I tried reinterpret_cast too, didn't work!
int main() { Student st, st2; //Student is the user-defined class. fstream data; data.open("student.txt", ios::in | ios::out); st.getdata(); //getdata() has string name, int roll number, int maths, int cp, and int total as members) data.write((char *) &st, sizeof(Student)); //it writes the data of object <st> to the file. data.seekg(0); data.read((char*) &st2, sizeof(Student)); //I wish to write the content of <st> object to <st2> object through the file "student.txt" st2.putdata(); //this gives me weird numbers. data.close(); return 0; }
2 Réponses
+ 3
Always check whether the file has been successfully opened before you do anything with it.
Most likely your "student.txt" does not exist and nothing gets read.
The values you see here are from when the Student class was constructed with its default values, garbage in this case.
You can use "data.open( "student.txt", std::ios::in | std::ios::out | std::ios::app );" to create a file, if it does not exist, and append data to it or "data.open( "student.txt", std::ios::in | std::ios::out | std::ios::trunc );" to create a file, if it does not exist, and erase its contents.
Also what you're doing only works if "std::is_trivially_copyable<Student>::value" returns true.
https://en.cppreference.com/w/cpp/named_req/TriviallyCopyable
If it returns false it's undefined behavior and your program will most likely crash.
( For example if you use an std::string object instead of a char[] for the name )
0
Typecasting is done to convert a datatype in to higher type.