[comp.lang.c] strrchr

jeffery@polari.UUCP (Jeffery Foy) (12/25/89)

Can someone tell/show me how to use this function?  I've never used it
before and some code that I got recently has it.  Any help will be
appreciated muchly...
 
Jeff
 
jeff@seaeast.wa.com  or  rutgers!rwing!seaeast!jeff

Bob.Stout@p6.f506.n106.z1.fidonet.org (Bob Stout) (12/26/89)

The strrchr() function is the ANSI equivalent of the older rindex() function  
(sort of - implementations differ). It returns a pointer to the last char in  
an array matching the char specified. Its equivalent function for matching  
the first char is strchr(). Example:

        char *test = "abcdefgfedcba";

        puts(strchr(test, 'd'));        /* prints "defgfedcba"  */
        puts(strrchr(test, 'd'));       /* prints "dcba"        */
 

john@chinet.chi.il.us (John Mundt) (12/27/89)

In article <1128@polari.UUCP> jeffery@polari.UUCP (Jeffery Foy) writes:
>
>Can someone tell/show me how to use this function?  I've never used it
>before and some code that I got recently has it.  Any help will be
>appreciated muchly...
> 

Assume you have a path to a file and want to find just the file name.
You could have just a relative path, foo.dat, or an absolute path,
/usr/you/docs/foo.dat.  Assume that the path is in char *path.

char *ptr, path[BUFSIZ];
	...

	ptr = strrchr(path, '/');
	printf("File is %s\n", ptr ? ptr + 1 : path);

	...

ptr will hold the location of the last / in the path, so ptr + 1
points to the file name.  If strrchr comes back as NULL, then the
pathname is relative.  strchr() does the same thing but finds
the first instance.  BSD uses index() and rindex() to do the same
thing.  

-- 
---------------------
John Mundt   Teachers' Aide, Inc.  P.O. Box 1666  Highland Park, IL
john@admctr.chi.il.us *OR* fred@teacha.chi.il.us
(312) 998-5007 (Day voice) || -432-8860 (Answer Mach) && -432-5386 Modem