exit(), abort() and assert() in C

exit(), abort() and assert() in C

exit(), abort() and assert() in C

rn

exit() in C

rn

exit() terminates the process normally. A status value of 0 or EXIT_SUCCESS, that is returned to the parent, denotes the successful execution of the function. On the other hand, getting a constant or EXIT_FAILURE denotes the failure in execution. exit() performs the following operations:

rn

It closes all the files that are open.
It flushes unwritten buffered data.
It removes the temporary files.
it returns an integer exit status to the operating system.

rn

Using atexit() will let you customize exit() to perform additional activities at program termination. 

rn

For example, 

rn

int main ()
{
FILE * pFile;
pFile = fopen (“file1.txt”, “r”);
if (pFile == NULL)
{
printf (“Error opening file”);
exit (1);
}
else
{
/* file operations here */
}
return 0;
}

rn

abort() in C

rn

abort() function is used to terminate the process. This termination of the process is done by raising a SIGABRT signal, and also, your program can include a handler to intercept this signal.

rn

For example,

rn

int main()
{
FILE *fp = fopen(“C:\file1.txt”, “w”);
if(fp == NULL)
{
printf(“n could not open file “);
getchar();
exit(1);
}
fprintf(fp, “%s”, “Face Prep”);
/* ……. */
/* ……. */
/* Something went wrong so terminate here */
abort();
getchar();
return 0;
}

rn

assert() in C

rn

By using assert(), the following happens:

rn

If expression evaluates to 0 (false), then the expression, sourcecode filename, and line number are sent to the standard error, and then abort() function is called.
Macro assert does nothing when the identifier NDEBUG (“no debug”) is defined with #define NDEBUG.

rn

Assertion failed: expression, file filename, line line-number is the form of the Common error outputting.

rn

For example,

rn

void open_record(char *record_name)
{
assert(record_name != NULL);
/* Rest of code */
}
int main(void)
{
open_record(NULL);
}

c