clinuxpathstrchr

Find absolute path in linux using strchr


How can we use the function strchr to find absolute path in linux, for example:

Input: /home/test/sample
Output: /home/test

I try to write something like this:

int main() {
char* string = "/home/test/sample";
char* pos;
pos = strchr(string, '/');
printf("%s\n", pos);
return 0;
}

But that's not working, I got the same output as the input:

Input: /home/test/sample
Output: /home/test/sample

Solution

  • Use the dirname function instead:

    #include <libgen.h>
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
      char* string = strdup ("/home/test/sample");
      char* pos;
      pos = dirname (string);
      printf ("%s\n", pos);
      return 0;
    }
    

    In order to search for the right most occurrence use the strrchr function.