954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

FILE * cleanup in destructor.

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)?

Drowzee
Posting Whiz in Training
245 posts since Jul 2005
Reputation Points: 22
Solved Threads: 5
 
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.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

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.

Drowzee
Posting Whiz in Training
245 posts since Jul 2005
Reputation Points: 22
Solved Threads: 5
 

A little info on this . My personal favourite is always seeing BAADF00D at the top of the call stack.

Stoned_coder
Junior Poster
164 posts since Jul 2005
Reputation Points: 19
Solved Threads: 5
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You