Exiting in C –  Program Tutorial

Hey there today I will show you two ways to exit your program in C language, I will make this simple as possible and include examples so you know how to use it.

To get started we will think with, success and error. Maybe our program has been interrupted or just a normal error so it needs to exit that way or maybe it was a success so it can exit that way. Here comes exit(0); and exit(1); these two can be used for this purpose.

 

How to use the exit?

Well exit(0); is used upon success on termination of the program, so its macro is EXIT_SUCCESS and as you could guess the exit(1); is used for error or interruption so its macro is EXIT_FAILURE

 

Examples

This example is used with just exit(0) ;

#include <file.h>
#include <stdio.h>

int main() {
FILE* file;

file = fopen(“myFile.txt”, “r”);
printf(“File opened successfully!”);
exit(0);
}

 

This example is used with both

#include <file.h>
#include <stdio.h>

int main() {
FILE* file;

file = fopen(“myFile.txt”, “r”);

if (file == NULL) {
printf(“Error, couldn’t open file!”);
exit(1);
}
exit(0);
}

 

Conclusion

Well I hope you enjoyed reading my simple tutorial on exiting with your C programs and I hoped it helped and wasn’t too confusing, if you have any questions feel free to comment. Read some other posts and stay tuned for the next one!

 

pentester

Leave a Reply