File rw and win32

Started by
1 comment, last by ursus 18 years, 1 month ago
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.
Advertisement
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.

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

This is it! Thank a lot Endurion. I knew I was missing something silly!

This topic is closed to new replies.

Advertisement