-
Multiple exits
Developing Windows based ‘C’ application. And following thing which annoys me a lot.
Say I am calling few CreateFile functions in my main function. Every time CreateFile function is invoked, it checks for result. And in each false statement I need to close and exit from application.
e.g.
Code:
HANDLE h1,h2,h3,h4;
h1 = CreateFile(..,..,..);
if ( false )
{
return;
}
h2 = CreateFile(..,..,..);
if (false)
{
CloseHandle(h1);
Exit;
}
h3 = CreateFile(..,..,..);
if (false)
{
CloseHandle(h1);
CloseHandle(h2);
Exit;
}
h4 = CreateFile(..,..,..);
if (false)
{
CloseHandle(h1);
CloseHandle(h2);
CloseHandle(h3);
Exit;
}
Firstly, do not like multiple exits in routine and on top these wrap up things. Can anybody suggest me any better way of doing it?
I can not use C++ at this moment.
Let me know
-
Code:
h1 = CreateFile(..,..,..);
h2 = CreateFile(..,..,..);
h3 = CreateFile(..,..,..);
h4 = CreateFile(..,..,..);
if( h1 == false || h2 == false || h3 == false || h4 == false )
{
if( h1 ) Close( h1 );
if( h2 ) Close( h2 );
if( h3 ) Close( h3 );
if( h4 ) Close( h4 );
Exit;
}
... do stuff ...
Something like that would work.
Quzah.
-
Or how about an array approach:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp[10];
int i;
char buf[BUFSIZ];
for (i = 0; i < 10; i++)
{
sprintf (buf, "file%d.txt", i);
if ((fp[i] = fopen(buf, "r")) == NULL)
break;
}
if (i != 10)
{
/* A file failed to open, close all previously opened files */
perror(buf);
while (i)
{
fclose(fp[--i]);
printf ("Closed file %d\n", i);
}
return EXIT_FAILURE;
}
puts ("All files opened");
/* Now use the files, then close them before finishing */
return 0;
}
/*
Example output:
file5.txt: No such file or directory
Closed file 4
Closed file 3
Closed file 2
Closed file 1
Closed file 0
*/