sephora sephora - 2 months ago 14
C Question

How to extract string from backtrace() ouput in C and store it in char*

I got the backtrace output as below

/home/jalv3/adv/adv2/local/libprog.so(func+0x2d) [0x8fe46911ac6d]


Now I want to extract only "libprog.so" and "0x8fe46911ac6d" and store it in a char *

Tried to use strtok and strchr as shown , but not getting the desired output

char * str = "/home/jalv3/adv/adv2/local/libprog.so(func+0x2d) [0x8fe46911ac6d]";
char * pp=strchr(str, '[');
char line[256];
char *subString;
strcpy(line, str);
subString = strtok(line,"/");
subString=strtok(NULL,"(");
printf("string 1= %s\n",pp);
printf("string 2 = %s\n",subString);


The output is

string 1 = [0x8fe46911ac6d]
string 2 = jalv3/adv/adv2/local/libprog.so

Answer

Simply continue parsing the string to get the result you want. For example, add the following code before the last printf to achieve the result you want.

/* subString = jalv3/adv/adv2/local/libprog.so at this point */

/* Reverse search to find the last '/' character */
subString = strrchr(subString, '/');

/* Jump past the '/' */
subString++

/* This will print: string 2 = libprog.so */
printf("string 2 = %s\n", subString);

I will leave the other string as an exercise for you.