Archived

This topic is now archived and is closed to further replies.

Program shutdown problem

This topic is 5898 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I just made a program to test what happened if I tried to open a file that didnt exist. In my OpenFile function I test if the file exist and if it doesnt it gives an error message and the program should shut down. I call this OpenFile function in another function which is in my main loop. After the OpenFile function call I have another function called WriteChar and that function would only work if the file had been opened which it is not. But the program doesnt shut down emmidiately. Once the shutdown function have run it ofcourse return to the function where OpenFile was called and that way WriteChar is also run. What I want the program to do is that when an error occurs it emmidiately shuts donw happens making sure nothing more in the program is run. One way I guess is to have every function give a return value which is checked and but I dont like that. Is there a way?

Share this post


Link to post
Share on other sites
there are a couple of ways. the easiest would be to call the ''exit()'' function, that shuts down immediatly, but a better way would be to do something like this.

void main()
{
some stuff...

try
{
openfile(lpszSomePath);
}
catch(...)
{
/* openfile failed, so we''ll quit */
exit(0); /*or whatever you need to do */
}

/*openfile obviously succeded, so do the stuff you want to */
writechar(file, "a"); /* your ''success'' code.
}

then you make the OpenFile function throw an exception when it fails, eg.

void OpenFile(const char* szPath)
{
FILE* pFile = fopen(szPath, "r");
if(!pFile)
{/*oh no, file doesn''t exist */
throw 1;
return;
}
/* file does exist */
}

allthough you could do better by making OpenFile return a bool value, true if it could open the file, false otherwise, then do this.

while(loop)
{
if(OpenFile(szName))
WriteChar(file, "z");
else
exit(0);
}

with this setup there is no way that writechar could be called, unless openfile succeeds.

Share this post


Link to post
Share on other sites