...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h>
int main(int argc, char **argv) {
/* ... */
if (/* something really bad happened */) {
return EXIT_FAILURE;
}
/* ... */
return EXIT_SUCCESS;
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> #include <stdio.h> int write_data(void) { const char *filename = "hello.txt"; FILE *f = fopen(filename, "w"); if (f == NULL) { /* Handle error */ } fprintf(f, "Hello, World\n"); /* ... */ abort(); /* Oops! Data might not be written! */ /* ... */ return 0; } int main(void) { write_data(); return 0EXIT_SUCCESS; } |
Compliant Solution
In this compliant solution, the call to abort()
is replaced with exit()
, which guarantees that buffered I/O data is flushed to the file descriptor and the file descriptor is properly closed.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> #include <stdio.h> int write_data(void) { const char *filename = "hello.txt"; FILE *f = fopen(filename, "w"); if (f == NULL) { /* Handle error */ } fprintf(f, "Hello, World\n"); /* ... */ exit(EXIT_FAILURE); /* Writes data and closes f. */ /* ... */ return 0; } int main(void) { write_data(); return 0EXIT_SUCCESS; } |
Although this particular example benefits from calling exit()
over abort()
, in some situations, abort()
is the better choice. Usually, abort()
is preferable when a programmer does not need to close any file descriptors or call any handlers registered with atexit()
, for instance, if the speed of terminating the program is critical.
...
[ISO/IEC 9899:2011] | Section 5.1.2.2.3, "Program Termination" Section 7.2022.4, "Communication with the Environment" |
...