Reputation: 573
I am trying to extract relative path name from absolute path name. Is there a function for this in C? Is there a function to print string starting from a particular character(I have the index)?
Upvotes: 0
Views: 482
Reputation: 57650
If you have the index you can do it quite easily.
char * src = "YOUR STRING";
char * dst; // destination
dst = (char *) malloc( sizeof(char) * 20);
dst = (char *)memcpy(dst, &src[THE_INDEX_YOU_KNOW], strlen(src)-THE_INDEX_YOU_KNOW);
dst[len-start]='\0';
Upvotes: 0
Reputation: 14408
As joseph mentioned, you can use basename().
Hope the following program helps a bit.
#include <stdio.h>
#include <stdlib.h>
#include <libgen.h>
#include <string.h>
int main ( int argc, char ** argv)
{
char *path = "/Users/lionnew/cpgm";
printf ("%s\n", basename (path));
/* If you have an index */
int index =15;
int len = strlen(path);
char * dest = malloc(len+1);
dest[len] = '\0';
strcpy (dest, (path+index));
printf ("\n Destination String %s ", dest);
}
NOTE: Make sure your index value is not geater than the string len to avoid segmentation fault.
Hope this helps to some extend. ;)
Upvotes: 0
Reputation: 9962
In POSIX.1-2001 (e.g. Linux), man 3 basename
gives:
The functions dirname() and basename() break a null-terminated pathname string into directory and filename components. In the usual case, ... basename() returns the component following the final '/'. Trailing '/' characters are not counted as part of the pathname.
Upvotes: 2