-3

I need to remove the last part of a file path.

For example, if I have this filename "user/doc/file1", I want to be able to get "user/doc/".

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Samun
  • 151
  • 1
  • 1
  • 12
  • "PS my qsn is different than the recommended solution" - if you ask for `realpath(".")` and take the last two elements of the returned path, I think you have a solution. _If_ I understand what you are asking correctly, that is! – davmac May 17 '18 at 15:03
  • If your question is different, please explain how, and also clarify what you are trying to do : ) – hat May 17 '18 at 15:04
  • Please elaborate your question, it's really unclear what you're asking. As your question stands here I'd just answer: "remove the `..` from `user/doc/..` to get `user/doc/`" – Jabberwocky May 17 '18 at 15:07
  • @MichaelWalz yea you understood my question. Any C library to do that parsing ? using strtok with separator ".." work? – Samun May 17 '18 at 15:12
  • @Samun so your question is totally misleading. Are you asking this: "I have a string that ends with `".."`. How can I remove the `".."` from the end of the string? Example: original string `"user/doc/.."`, string I want: `"user/doc/"`. – Jabberwocky May 17 '18 at 15:18
  • @MichaelWalz sorry that my qsn being unclear. So if i have a string "user/doc/file1", I want to remove "file1" and expect the final result be user/doc/. – Samun May 17 '18 at 15:44
  • @Samun please [edit] your question and make clear what _exactly_ you want. Your last comment isn't very clear either. Don't be sorry if your question is not clear, but make it clear instead. – Jabberwocky May 17 '18 at 15:46
  • @MichaelWalz I just edited. hope that helps. – Samun May 17 '18 at 15:47
  • @Samun please don't put clarfifications in comment but **[edit]** your question and make all clarifications _there_. Or just ask a new question and delete this one. – Jabberwocky May 17 '18 at 15:48
  • @MichaelWalz i updated qsn too. – Samun May 17 '18 at 15:50

1 Answers1

1

You probably want this:

#include <stdio.h>
#include <string.h>

int main()
{
  char string[] = "/user/doc/file1";

  // find pointer to last '/' in string
  char *lastslash = strrchr(string, '/');

  if (lastslash)           // if found
    *(lastslash + 1) = 0;  //   terminate the string right after the '/'

  printf ("string = %s\n", string);
}

Output

string = /user/doc/
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115