Wanted: How to strip off pathnames to obtain filenames.

Arthur David Olson ado at elsie.UUCP
Sun Sep 4 07:30:09 AEST 1988


> Almost.  It should be:
> 
> 	#include <stdio.h>
> 	#include <string.h>
> 
> 	main(argc, argv)
> 		int argc; char *argv[];
> 	{
> 		char *ptr;
> 
> 		if ((ptr = strchr(argv[1], '/')) == NULL)
> 			ptr = argv[1];
> 		else
> 			ptr++;
> 
> 		puts(ptr);
> 	}

Let's try again:

	#ifndef lint
	#ifndef NOID
	static char	sccsid[] = "@(#)usend.c	1.1";
	#endif /* !defined NOID */
	#endif /* !defined lint */

	#include <stdio.h>
	#include <string.h>

	#ifndef EXIT_SUCCESS
	#define EXIT_SUCCESS	0
	#endif /* !defined EXIT_SUCCESS */

	#ifndef EXIT_FAILURE
	#define EXIT_FAILURE	1
	#endif /* !defined EXIT_FAILURE */

	extern int	optind;

	int
	main(argc, argv)
	int	argc;
	char *	argv[];
	{
		register char *	ptr;

		if (getopt(argc, argv, "") != EOF || optind != argc - 1) {
			(void) fprintf(stderr, "%s: usage is %s filename\n",
				argv[0], argv[0]);
			exit(EXIT_FAILURE);
		}
		if ((ptr = strrchr(argv[optind], '/')) == NULL)
			ptr = argv[optind];
		else	++ptr;
		(void) puts(ptr);
		if (ferror(stdout) || fflush(stdout)) {
			(void) fprintf(stderr,
				"%s: wild result writing standard output\n",
				argv[0]);
			exit(EXIT_FAILURE);
		}
		exit(EXIT_SUCCESS);
		/*NOTREACHED*/
	}

Notes:

1.	The program now return an exit status.
2.	The program now checks that it is being used correctly.
	In particular, it avoids potential NULL pointer dereferencing if you use
		usend
	by itself on the command line.
3.	The program prints a usage message if it detects incorrect usage.
4.	The program checks that the output it generated actually got out
	(rather than, say, being directed to a full disk).
5.	The program calls getopt, even though it has no options, so that
	this program will handle "--", as in
		usend -- -a/b
	as other "standard" programs do.

Of course, around this neck of the woods we just "basename".
-- 
	ado at ncifcrf.gov			ADO is a trademark of Ampex.



More information about the Comp.unix.questions mailing list