exit() and reading text file

I'm learning about reading text files, and it says to use the exit() function to check and make sure the file was opened. Similar to this:
1
2
3
4
5
6
7
8
cin.getline(filename, SIZE);
	inFile.open(filename);	// associate inFile with a file
	if ( !inFile.is_open())	// failed to open file
	{
		cout << "Could not open the file " << filename << endl;
		cout << "Program terminating.\n";
		exit(EXIT_FAILURE);
	}

Now I don't doubt that this is correct, and better than do what I'm about to propose, but am wondering why. Could you not change the code to do this:

1
2
3
4
5
6
7
8
cin.getline(filename, SIZE);
	inFile.open(filename);	// associate inFile with a file
	if ( !inFile.is_open())	// failed to open file
	{
		cout << "Could not open the file " << filename << endl;
		cout << "Program terminating.\n";
		return 1;
	}


Why should I use exit() instead of just using return to end the program here if needed?
exit()'s use is more for outside of main(). While you can use exit() or return to similar effect in main(), inside other functions you can use exit() to terminate the program where return would only return the flow back to main().

-Albatross
True. That said, you should try to avoid structuring your program to need to use exit() or to otherwise abort if something goes wrong, unless your program simply cannot proceed.
Topic archived. No new replies allowed.