I'm making a program (using MFC) that opens a file using the c-style FILE* format rather than C++ style streams.
I'm doing this because I'm lazy, and so I can use as much pre-existing code as I can.

When I close the program, a destructor is called.

CGrid1Doc::~CGrid1Doc()
{
	if(packfile!=NULL)
		fclose(packfile);
}

where packfile is a FILE* object.
However, when I start the program, packfile defaults to 0xcdcdcdcd.
With the above destructor, this means that fclose creates an access violation in the event that the program exits without having first opened a file.

Can I safely use this instead, or is it just bad practice and possibly non-portable?

CGrid1Doc::~CGrid1Doc()
{
	if(packfile!=0xcdcdcdcd)
		fclose(packfile);
}

Edit: and if I can't, how could I do this in C (preferably without a flag)?

Recommended Answers

All 3 Replies

However, when I start the program, packfile defaults to 0xcdcdcdcd.

Isn't that a Microsoft-specific debug-only kinda thingy?

Does this happen when you explicitly set the pointer to NULL in the constructor?


[edit]I didn't read all of this, but it looks like it discusses the 0xcdcdcdcd value.

Isn't that a Microsoft-specific debug-only kinda thingy?

Does this happen when you explicitly set the pointer to NULL in the constructor?


[edit]I didn't read all of this, but it looks like it discusses the 0xcdcdcdcd value.

I just had a feeling that 0xcdcdcdcd was too arbitrary (and repeating on every compile) to be a safe value.

I'm now setting the File* to null in the constructor, and things seem to be working fine. Thanks for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.