Use the return statement to leave a function, this is the graceful way.
Use the exit() call to exit your program, but this isn't graceful.
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
if ((fp = fopen("file.txt", "r")) == NULL)
{
perror("file.txt");
return (EXIT_FAILURE);
}
printf ("File opened successfully\n");
fclose(fp);
return (EXIT_SUCCESS);
}
If you're going to return from a function, make sure you return something that denotes the failure. Likes this:
Code:
#include <stdio.h>
#include <stdlib.h>
int DoIt(FILE *fp);
int main(void)
{
FILE *fp;
if ((fp = fopen("file.txt", "r")) == NULL)
{
perror("file.txt");
return (EXIT_FAILURE);
}
printf ("File opened successfully\n");
if (DoIt(fp) < 0)
printf ("Error in function do it\n");
fclose(fp);
return (EXIT_SUCCESS);
}
int DoIt(FILE *fp)
{
char buf[BUFSIZ];
if (fgets(buf, sizeof buf, fp) == NULL)
return -1;
printf ("buf is %s", buf);
return 0;
}