Writing files to disk

Started by
5 comments, last by dot 19 years, 7 months ago
I have a struct that holds a pointer to a byte array and I'm having a hard time writing this to the disk. What is the best approach to take? Thanks
Advertisement
#include <fstream>int main(){	struct mystruct	{		char* ptr;	};	mystruct data;	data.ptr = new unsigned char [500];	std::ofstream file;	file.open("output.dat");	file.write(data.ptr, sizeof (unsigned char)*500);	file.close();	delete [] data.ptr;}
Coming from the C realm, I'm curious how using fstream compares to just using posix calls directly? fstream certainly looks cleaner in your example (and much nicer than the "file << data1 << data2" ofstream methods I've seen until now, which I've been avoiding like the plague), but it makes me wonder why, with posix available.

Just as a curiosity. A portable method already exists, and then this other (also portable) method is created. Makes me wonder what the tradeoffs are. I know, posix is the "old C way", and this is C++ now, but is that all?
fstream is standard C++, which means any compliant compiler must have it. POSIX might be implemented, but it might not. You're much better sticking to language standards than OS/API/Whatever standards, especially when (afaik) windows doesn't implement POSIX (and MSVC doesn't emulate it).

EDIT: Unless you're talking about Cs fopen which I guess might be POSIX. If that is what you're talking about, well its also standard 'old C'(meaning its in the C that C++ is 'almost backwards compatabile' with), so you can use it just fine in C++ as well. In that case, it is purely preference. If you don't mind taking care of cleanup yourself, then there is no reason you couldn't use fopen etc.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
Quote: If you don't mind taking care of cleanup yourself, then there is no reason you couldn't use fopen etc.


what cleanup is involved with fopen? I thought fclose took care of that.
You have to remember calling fclose. With stream objects, if you allocate them on the stack, the destructor gets automatically called. If the destructor fails (say, some flushing I/O error), it has to throw an execption at that point.
enum Bool { True, False, FileNotFound };
Quote:Original post by hplus0603
You have to remember calling fclose. With stream objects, if you allocate them on the stack, the destructor gets automatically called. If the destructor fails (say, some flushing I/O error), it has to throw an execption at that point.


Destructors that throws an exception are evil. All destructors should be written as if the no-throw specifier is there (As if, and there are arguments still as to if it should be physically there or not). But still, destructors should never throw.

Meyer (or was it Sutter) had an excellent explaination in his book (either the Effective series, or the Exceptional series. But I rather you read all of them ;)

This topic is closed to new replies.

Advertisement