'exit(1);' considered useless (suggestion for improvement)

Ian F. Darwin ian at utcsstat.UUCP
Sun Feb 12 14:10:51 AEST 1984


	I agree that "can't open file" isn't informative enough (UNIX isn't the
	only sinner here, though; RSX-11M error messages also just say "sorry,
	couldn't do it"), but one reason may be that it's a pain in the *ss to
	get "perror" to say:
	
		frob: /etc/mumble: No such file or directory
	
	Neither perror("frob") nor perror(filename) do what you really want (and
	for the "link" system call, you usually want to print *both* names, which
	"perror" won't let you).  The answer is to use "sys_errlist" and use
	"fprintf" (not "printf", please, don't send error messages to stdout!) to
	print the message.
	
		Guy Harris
		{seismo,ihnp4,allegra}!rlgvax!guy

It's actually very easy to get the effect of perror(3) with a real message.
A good encapsulation of this technique appears in the Kernighan and Pike
book ``The UNIX Programming Environment''. The function
	error(s1, s2);
prints out the program name (the first line in `main' has to be
	progname = argv[0];
for this to work), then s1 and s2 (which should be either a printf
format and arg, or a simple string and null ptr), then iff there is a reasonable
value of errno and sys_errlist[errno] this too is printed. So you get:
	foo: can't read bar (No such file or directory)
just by saying
	error("can't read %s", barfile);

It would be nice if people would adopt this as a kind of `standard';
since it will be quite widely known as a result of the book, I would
say that it's probably reasonable to distribute code which calls this
function (and others in the book, such as efopen() which encapulates
the common and tedious
	if ((x=fopen(bar, "r")) == NULL) {
		... print a message ...
		exit(1);
	}
into a single call,
	x=efopen(bar, "r);

There is a lot of other good code in the book as well, but these
encapsulations are SOOOO useful that I recommend we all use them.


Ian F. Darwin, Toronto, Canada     decvax!utcsstat!darwin!ian



More information about the Comp.lang.c mailing list