DEV Community

Discussion on: A Comprehensive Guide on File Handling in C++

Collapse
 
pauljlucas profile image
Paul J. Lucas • Edited
std::ofstream *file = new std::ofstream();

There is no reason to dynamically allocate the file in your example. It's actually worse if you do because then you don't benefit from RAII, in this case the fact that the destructor will automatically flush and close the file upon destruction.

Even if you do dynamically allocate objects, you should never use native pointers, but something like std::unique_ptr.

this->name = ""

There's no reason to initialize a std::string like this since it has a default constructor that does the same thing, except more efficiently. Also, you forgot the ;.

out_file->write(reinterpret_cast<char*>&student, sizeof(student));

That's the wrong way to write that out. You're writing out implementation-defined bytes, both that the compiler may introduce to your class for padding, and also for std::string itself. It's also not portable.

The correct way is to overload << for Student like:

std::ostream& operator<<( std::ostream &o, Student const &s ) {
    return o << s.name << ',' << s.age;
}
Enter fullscreen mode Exit fullscreen mode

where you choose a serialization format yourself. You would then also overload >> to deserialize the object.