firouzehsm

Hi,

I am using Visual C++ 6 under Windows XP Professional 2002. I have a simple program, that catches an exception, sets a valid errorid using SetLastError and reads the errorid later somewhere else in the program using GetLastError. But the code that is returned from GetLastError is not what I set, as if SetLastError didn't work.

To make sure that my SetLastError is the last one that sets the errorid for this thread, I wrote a test program. I set the error using SetLastError and read it immediately after using GetLastError, again the errorid was not set. During my experiments, though, it set the errorid once but I could not overwrite it again. GetLastError returned that same errorid in all subsequent program runs , although I was changing it in SetLastError! I restarted Windows and ran the program again, I got the same id!

Here is my test code. It is a simple Win32 Console program:

SetLastError(0); /* I change the value of this id in different tests. */

FILE *pFile = NULL;

if ( (pFile=fopen("C:\\test.txt", "a")) != NULL )

{

fprintf(pFile, "LastError=%d \n", GetLastError());

fclose(pFile);

}

I was wondering if there is a known issue with Set/GetLastError under Windows XP Pro. My original program is relying on this errorid. I would appreciate any thoughts/helps on this.

Thanks,

Firouzeh



Re: Visual C++ General Why SetLastError doesn't work?

Paul Marriott

SetLastError will only work in this instance if you check the reply value with GetLastError Before any other function that uses SetLastError is called, Thus to do what you are doing the call as follows:

Function:

int Func()

{

SetLastError(x);

return 0;

}

code...

if (Func()==0)

{

errorcode=GetLastError();

do other stuff;

}

else

do other stuff;





Re: Visual C++ General Why SetLastError doesn't work?

Sdi

That's the downside of using the Unix-style I/O functions: you don't know what's going on under the covers. The documentation for fopen() makes no mention of [Get|Set]LastError(). However, fopen ultimately ends up in CreateFile(), which does:

"If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError."

Many Win32 API functions call SetLastError() when they fail; any function that tells you to call GetLastError() if the function returns an error code means that that function calls SetLastError() on failure. Don't rely on your SetLastError() value being preserved across any function call unless you know the entire call chain that might result from that call and have verified that nothing in that call chain calls SetLastError().





Re: Visual C++ General Why SetLastError doesn't work?

firouzehsm

Thanks Paul and Sdi. I called GetLastError right after setting the id and it worked fine. Nice catch, thank you very much...

Firouzeh