Sign in to follow this  
ursus

File rw and win32

Recommended Posts

ursus    206
Coders, I stumbled across something I don’t really understand. Let me just quickly present a bit of code:
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	FILE *log;

	switch(msg)
	{
		case WM_CREATE:
		{
			log = fopen("log.txt", "a");
			fprintf (log, "Program started");
		}
		break;
		
		case WM_CLOSE:
			DestroyWindow(hwnd);
		break;
		
		case WM_DESTROY:
		{	
			fprintf (log, "Program closed");
			fclose (log);
						
			PostQuitMessage(0);
		}
		break;
		default:
			return DefWindowProc(hwnd, msg, wParam, lParam);
	}
	return 0;
}


Just a standard WinProc followed by a standard WinMain. For some reason when I close the window – apparently when it comes to the file manipulation lines the program crashes. Any suggestions on what I am doing wrong? Tons of thanks in advance.

Share this post


Link to post
Share on other sites
Endurion    5411
Your FILE* log is inside the scope of the WndProc. For every message your WndProc receives a new FILE* log is created on the stack and discarded on leaving the function.

So on WM_DESTROY you're trying to write to an uninitialized FILE* handle.

Either have A) a global FILE* log somewhere, B) make it static FILE* log or C) have a logging class that takes care of the file handle and stays alive outside the WndProc function.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this