0

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
ceving
  • 21,900
  • 13
  • 104
  • 178
Pedro Gómez
  • 214
  • 1
  • 8
  • Quote from the manual page: *The strchr() function returns a pointer to the first occurrence of the character c in the string s.* This first occurrence is the left most, which is the first character. – ceving Jun 10 '21 at 08:38
  • 1
    You are using the wrong terminology. Technically what you are looking for is the pathname prefix. – fpmurphy Jun 10 '21 at 13:04
  • From the code sample, it appears that you do not actually want the absolute path. If you do want the absolute path, try `realpath` – William Pursell Jun 10 '21 at 15:50

1 Answers1

1

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.

ceving
  • 21,900
  • 13
  • 104
  • 178