[comp.lang.c] Wanted: How to strip off pathnames to obtain filenames.

ado@elsie.UUCP (Arthur David Olson) (09/04/88)

> 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@ncifcrf.gov			ADO is a trademark of Ampex.

gandalf@csli.STANFORD.EDU (Juergen Wagner) (09/06/88)

If you are using csh, how about:

	% set foo = /usr/john/foo/bar/src/misc/other/bugs/nil.bang
	% echo ${foo:t}
	nil.bang
	%

-- 
Juergen "Gandalf" Wagner,		   gandalf@csli.stanford.edu
Center for the Study of Language and Information (CSLI), Stanford CA

levy@ttrdc.UUCP (Daniel R. Levy) (09/06/88)

In article <8129@elsie.UUCP>, ado@elsie.UUCP (Arthur David Olson) writes:
[lotsa C code]

how 'bout

	echo $FILENAME | awk -F/ '{print $NF}'

simple huh?
-- 
|------------Dan Levy------------|  THE OPINIONS EXPRESSED HEREIN ARE MINE ONLY
| Bell Labs Area 61 (R.I.P., TTY)|  AND ARE NOT TO BE IMPUTED TO AT&T.
|        Skokie, Illinois        | 
|-----Path:  att!ttbcad!levy-----|