#include <stdio.h> /* fprintf */
#include <errno.h> /* errno */
#include <string.h> /* strerror */
extern int errno ;
int main ()
{
FILE * pf;
errno = 0;
pf = fopen ("notexist.txt", "r");
if (errno || pf == NULL)
{
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error");
fprintf(stderr, "fopen failed due to: %s\n", strerror( errno));
}
else
{
fclose (pf);
}
return 0;
}
Value of errno : 2
Error : No such file or directory
fopen failed due to : No such file or directory
It is a common problem that at the time of dividing any number, programmers do not check if a divisor is zero and finally it creates a runtime error.
#include <stdio.h>
#include <stdlib.h>
main() {
int dividend = 20;
int divisor = 0;
int quotient;
if( divisor == 0){
fprintf(stderr, "Division by zero! Exiting...\n");
exit(-1);
}
quotient = dividend / divisor;
fprintf(stderr, "Value of quotient : %d\n", quotient );
exit(0);
}
Division by zero! Exiting...
It is a common practice to exit with a value of EXIT_SUCCESS in case of program coming out after a successful operation. Here, EXIT_SUCCESS is a macro and it is defined as 0.
If you have an error condition in your program and you are coming out then you should exit with a status EXIT_FAILURE which is defined as -1.
#include <stdio.h>
#include <stdlib.h>
main() {
int dividend = 20;
int divisor = 5;
int quotient;
if( divisor == 0) {
fprintf(stderr, "Division by zero! Exiting...\n");
exit(EXIT_FAILURE);
}
quotient = dividend / divisor;
fprintf(stderr, "Value of quotient : %d\n", quotient );
exit(EXIT_SUCCESS);
}
Value of quotient : 4